From 8d20e4d64db0118da5fe9a3fa1130c5b5bef18f7 Mon Sep 17 00:00:00 2001 From: Josh Berdine Date: Wed, 13 Nov 2019 05:37:12 -0800 Subject: [PATCH] [ocamlformat] Upgrade ocamlformat version Reviewed By: jvillard Differential Revision: D18162727 fbshipit-source-id: ffb9f7541 --- Makefile | 2 +- infer/src/.ocamlformat | 3 +- infer/src/IR/AccessPath.ml | 2 +- infer/src/IR/Annot.ml | 6 +- infer/src/IR/Annot.mli | 2 +- infer/src/IR/Attributes.ml | 5 +- infer/src/IR/Binop.ml | 1 + infer/src/IR/Binop.mli | 1 + infer/src/IR/DecompiledExp.ml | 5 +- infer/src/IR/Errlog.ml | 6 +- infer/src/IR/Exp.mli | 6 +- infer/src/IR/HilExp.ml | 16 +- infer/src/IR/HilInstr.ml | 8 +- infer/src/IR/Ident.ml | 4 +- infer/src/IR/Ident.mli | 6 +- infer/src/IR/Localise.ml | 12 +- infer/src/IR/Mangled.mli | 4 +- infer/src/IR/Objc_models.ml | 6 +- infer/src/IR/Procdesc.ml | 30 ++-- infer/src/IR/Procdesc.mli | 10 +- infer/src/IR/ProcnameDispatcher.ml | 22 +-- infer/src/IR/ProcnameDispatcher.mli | 6 +- infer/src/IR/Pvar.ml | 7 +- infer/src/IR/Sil.ml | 30 +--- infer/src/IR/Sil.mli | 4 +- infer/src/IR/SourceFiles.ml | 8 +- infer/src/IR/SpecializeProcdesc.ml | 14 +- infer/src/IR/Tenv.ml | 2 +- infer/src/IR/Typ.ml | 12 +- infer/src/IR/Typ.mli | 18 +- infer/src/IR/WeakTopologicalOrder.ml | 8 +- infer/src/IR/WeakTopologicalOrder.mli | 2 +- infer/src/absint/AbstractDomain.ml | 3 +- infer/src/absint/AbstractDomain.mli | 74 ++++---- infer/src/absint/AbstractInterpreter.ml | 9 +- infer/src/absint/AbstractInterpreter.mli | 8 +- infer/src/absint/LowerHil.ml | 4 +- infer/src/absint/LowerHil.mli | 20 +-- infer/src/absint/PatternMatch.ml | 4 +- infer/src/absint/ProcCfg.ml | 10 +- infer/src/absint/ProcCfg.mli | 11 +- infer/src/absint/SummaryPayload.ml | 6 +- infer/src/absint/SummaryPayload.mli | 3 +- infer/src/absint/TransferFunctions.mli | 8 +- infer/src/al/AL.ml | 5 +- infer/src/al/ALIssues.ml | 23 ++- infer/src/al/ALUtils.ml | 3 +- infer/src/al/CTLExceptions.mli | 4 +- infer/src/al/ComponentKit.ml | 16 +- infer/src/al/cPredicates.ml | 22 +-- infer/src/al/cPredicates.mli | 3 +- infer/src/al/cTL.ml | 8 +- infer/src/al/ctl_parser_types.ml | 21 ++- infer/src/al/tableaux.ml | 16 +- infer/src/backend/BackendStats.ml | 6 +- infer/src/backend/CallGraph.ml | 5 +- infer/src/backend/CallGraph.mli | 3 +- infer/src/backend/Differential.ml | 7 +- infer/src/backend/DifferentialFilters.ml | 5 +- infer/src/backend/ExternalPerfData.ml | 3 +- infer/src/backend/InferAnalyze.ml | 14 +- infer/src/backend/InferPrint.ml | 27 +-- infer/src/backend/OndemandCapture.ml | 12 +- infer/src/backend/Payloads.mli | 49 +++--- infer/src/backend/PerfStats.ml | 2 +- infer/src/backend/SpecsFiles.ml | 4 +- infer/src/backend/StatsAggregator.ml | 3 +- infer/src/backend/callbacks.ml | 3 +- infer/src/backend/dotty.ml | 41 ++--- infer/src/backend/errdesc.ml | 14 +- infer/src/backend/errdesc.mli | 3 +- infer/src/backend/exe_env.ml | 4 +- infer/src/backend/mergeCapture.ml | 3 +- infer/src/backend/ondemand.ml | 13 +- infer/src/backend/preanal.ml | 2 +- infer/src/backend/reporting.ml | 8 +- infer/src/base/CommandDoc.ml | 42 +++-- infer/src/base/CommandLineOption.ml | 32 ++-- infer/src/base/CommandLineOption.mli | 3 +- infer/src/base/Config.ml | 96 +++++------ infer/src/base/DBWriter.ml | 43 +++-- infer/src/base/Die.mli | 2 +- infer/src/base/IssueType.ml | 5 +- infer/src/base/JsonBuilder.ml | 4 +- infer/src/base/Logging.ml | 10 +- infer/src/base/Logging.mli | 4 +- infer/src/base/PerfEvent.ml | 2 +- infer/src/base/ProcessPool.ml | 37 ++-- infer/src/base/ResultsDir.ml | 7 +- infer/src/base/RunState.ml | 3 +- infer/src/base/SourceFile.ml | 4 +- infer/src/base/SourceFile.mli | 4 +- infer/src/base/SqliteUtils.ml | 12 +- infer/src/base/SqliteUtils.mli | 2 +- infer/src/base/SymOp.ml | 2 +- infer/src/base/SymOp.mli | 2 +- infer/src/base/TaskBar.ml | 3 +- infer/src/base/Utils.ml | 4 +- infer/src/base/ZipLib.ml | 6 +- infer/src/biabduction/Abs.ml | 8 +- infer/src/biabduction/Absarray.ml | 12 +- infer/src/biabduction/BiabductionSummary.mli | 2 +- infer/src/biabduction/Buckets.ml | 7 +- infer/src/biabduction/BuiltinDefn.ml | 53 +++--- infer/src/biabduction/BuiltinDefn.mli | 2 +- infer/src/biabduction/Dom.ml | 123 +++++++------- infer/src/biabduction/Match.ml | 4 +- infer/src/biabduction/Paths.ml | 2 +- infer/src/biabduction/Prop.ml | 32 ++-- infer/src/biabduction/Prop.mli | 3 +- infer/src/biabduction/Propgraph.mli | 3 +- infer/src/biabduction/Prover.ml | 42 ++--- infer/src/biabduction/Rearrange.ml | 58 +++---- infer/src/biabduction/Rearrange.mli | 3 +- infer/src/biabduction/RetainCyclesType.ml | 11 +- infer/src/biabduction/RetainCyclesType.mli | 2 +- infer/src/biabduction/State.ml | 7 +- infer/src/biabduction/State.mli | 7 +- infer/src/biabduction/SymExec.ml | 66 ++++---- infer/src/biabduction/SymExecBlocks.ml | 9 +- infer/src/biabduction/Tabulation.ml | 30 ++-- infer/src/bufferoverrun/absLoc.ml | 80 ++++----- infer/src/bufferoverrun/bounds.ml | 17 +- .../bufferoverrun/bufferOverrunAnalysis.ml | 4 +- .../src/bufferoverrun/bufferOverrunChecker.ml | 23 +-- .../src/bufferoverrun/bufferOverrunDomain.ml | 27 ++- .../bufferOverrunDomainRelation.ml | 12 +- infer/src/bufferoverrun/bufferOverrunField.ml | 3 +- .../src/bufferoverrun/bufferOverrunModels.ml | 33 ++-- .../bufferOverrunProofObligations.ml | 65 ++++--- .../bufferoverrun/bufferOverrunSemantics.ml | 18 +- infer/src/bufferoverrun/bufferOverrunTrace.ml | 9 +- infer/src/bufferoverrun/bufferOverrunUtils.ml | 11 +- infer/src/bufferoverrun/itv.ml | 6 +- infer/src/bufferoverrun/polynomials.ml | 8 +- infer/src/bufferoverrun/symb.ml | 103 ++++++------ infer/src/bufferoverrun/symb.mli | 6 +- infer/src/checkers/LithoFramework.ml | 7 +- infer/src/checkers/NullabilityPreanalysis.ml | 2 +- infer/src/checkers/RequiredProps.ml | 28 ++-- infer/src/checkers/Siof.ml | 10 +- infer/src/checkers/Trace.ml | 21 +-- infer/src/checkers/Trace.mli | 13 +- infer/src/checkers/accessTree.ml | 9 +- infer/src/checkers/annotationReachability.ml | 11 +- infer/src/checkers/annotations.ml | 4 +- infer/src/checkers/classLoads.ml | 2 +- infer/src/checkers/control.ml | 6 +- infer/src/checkers/control.mli | 6 +- infer/src/checkers/cost.ml | 36 ++-- infer/src/checkers/costModels.ml | 12 +- infer/src/checkers/dataflow.ml | 4 +- .../checkers/fragmentRetainsViewChecker.ml | 4 +- infer/src/checkers/hoisting.ml | 4 +- infer/src/checkers/impurity.ml | 3 +- infer/src/checkers/impurityDomain.ml | 3 +- infer/src/checkers/liveness.ml | 3 +- infer/src/checkers/liveness.mli | 6 +- infer/src/checkers/loopInvariant.ml | 13 +- infer/src/checkers/loopInvariant.mli | 10 +- infer/src/checkers/purity.ml | 10 +- infer/src/checkers/purityModels.ml | 9 +- infer/src/checkers/reachingDefs.ml | 4 +- infer/src/checkers/reachingDefs.mli | 4 +- infer/src/checkers/uninit.ml | 10 +- infer/src/checkers/uninitDomain.ml | 10 +- infer/src/clang/CType_decl.ml | 26 ++- infer/src/clang/Capture.ml | 3 +- infer/src/clang/ClangCommand.ml | 22 ++- infer/src/clang/ClangWrapper.ml | 59 ++++--- infer/src/clang/ast_expressions.ml | 4 +- infer/src/clang/cArithmetic_trans.ml | 3 +- infer/src/clang/cAst_utils.ml | 14 +- infer/src/clang/cAst_utils.mli | 6 +- infer/src/clang/cFrontend_config.ml | 4 +- infer/src/clang/cFrontend_decl.ml | 19 +-- infer/src/clang/cFrontend_errors.ml | 4 +- infer/src/clang/cGeneral_utils.ml | 7 +- infer/src/clang/cGeneral_utils.mli | 3 +- infer/src/clang/cLocation.ml | 3 +- infer/src/clang/cMethodSignature.ml | 6 +- infer/src/clang/cMethod_trans.ml | 8 +- infer/src/clang/cScope.ml | 2 +- infer/src/clang/cTrans.ml | 158 ++++++------------ infer/src/clang/cTrans_models.ml | 5 +- infer/src/clang/cTrans_utils.ml | 22 +-- infer/src/clang/cTrans_utils.mli | 8 +- infer/src/clang/cVar_decl.ml | 13 +- infer/src/concurrency/ConcurrencyModels.ml | 14 +- infer/src/concurrency/ExplicitTrace.mli | 6 +- infer/src/concurrency/MethodMatcher.ml | 3 +- infer/src/concurrency/RacerD.ml | 55 +++--- infer/src/concurrency/RacerDDomain.ml | 6 +- infer/src/concurrency/RacerDModels.ml | 12 +- infer/src/concurrency/StarvationModels.ml | 4 +- infer/src/concurrency/starvation.ml | 4 +- infer/src/concurrency/starvationDomain.ml | 25 +-- infer/src/concurrency/starvationDomain.mli | 4 +- infer/src/dune.in | 6 +- infer/src/infer.ml | 6 +- .../integration/CaptureCompilationDatabase.ml | 7 +- .../CaptureCompilationDatabase.mli | 3 +- infer/src/integration/CompilationDatabase.ml | 6 +- infer/src/integration/Driver.ml | 21 +-- infer/src/integration/Maven.ml | 2 +- infer/src/istd/ARList.mli | 58 +++---- infer/src/istd/Escape.ml | 2 +- infer/src/istd/GOption.ml | 3 +- infer/src/istd/IContainer.mli | 3 +- infer/src/istd/IStd.ml | 8 +- infer/src/istd/ImperativeUnionFind.ml | 2 +- infer/src/istd/MaximumSharing.ml | 9 +- infer/src/istd/StatisticsToolbox.ml | 9 +- infer/src/java/JProcname.ml | 8 +- infer/src/java/jClasspath.ml | 4 +- infer/src/java/jContext.mli | 2 +- infer/src/java/jMain.ml | 4 +- infer/src/java/jTrans.ml | 16 +- infer/src/java/jTransExn.ml | 3 +- infer/src/java/jTransType.ml | 8 +- .../labs/00_dummy_checker/ResourceLeaks.ml | 6 +- .../labs/01_integer_domain/ResourceLeaks.ml | 2 +- .../src/labs/02_domain_join/ResourceLeaks.ml | 2 +- infer/src/labs/03_domain_top/ResourceLeaks.ml | 2 +- .../labs/04_interprocedural/ResourceLeaks.ml | 2 +- .../ResourceLeakDomain.ml | 3 +- .../ResourceLeaks.ml | 2 +- infer/src/labs/ResourceLeaks.ml | 2 +- infer/src/nullsafe/AnnotatedSignature.ml | 8 +- infer/src/nullsafe/AssignmentRule.ml | 9 +- infer/src/nullsafe/AssignmentRule.mli | 4 +- infer/src/nullsafe/InferredNullability.ml | 4 +- infer/src/nullsafe/InheritanceRule.ml | 5 +- infer/src/nullsafe/Initializers.ml | 10 +- infer/src/nullsafe/NullabilityCheck.ml | 12 +- infer/src/nullsafe/NullabilitySuggest.ml | 10 +- infer/src/nullsafe/OverAnnotatedRule.ml | 4 +- .../src/nullsafe/ThirdPartyAnnotationInfo.ml | 3 +- infer/src/nullsafe/eradicate.ml | 7 +- infer/src/nullsafe/eradicateChecks.ml | 31 ++-- infer/src/nullsafe/modelTables.ml | 11 +- infer/src/nullsafe/models.ml | 2 +- infer/src/nullsafe/typeCheck.ml | 61 +++---- infer/src/nullsafe/typeCheck.mli | 3 +- infer/src/nullsafe/typeErr.ml | 3 +- infer/src/pulse/Pulse.ml | 9 +- infer/src/pulse/PulseAbductiveDomain.ml | 40 +++-- infer/src/pulse/PulseArithmetic.ml | 58 +++---- infer/src/pulse/PulseBaseDomain.ml | 8 +- infer/src/pulse/PulseDiagnostic.ml | 8 +- infer/src/pulse/PulseDiagnostic.mli | 4 +- infer/src/pulse/PulseDomainInterface.ml | 4 +- infer/src/pulse/PulseModels.ml | 7 +- infer/src/pulse/PulseOperations.ml | 3 +- infer/src/pulse/PulseTrace.ml | 3 +- infer/src/quandary/ClangTaintAnalysis.ml | 16 +- infer/src/quandary/ClangTrace.ml | 13 +- infer/src/quandary/JavaTaintAnalysis.ml | 6 +- infer/src/quandary/JavaTrace.ml | 12 +- infer/src/quandary/TaintAnalysis.ml | 39 ++--- infer/src/quandary/quandaryBO.ml | 5 +- infer/src/scripts/checkCopyright.ml | 3 +- infer/src/scuba/Scuba.ml | 2 +- .../src/test_determinator/testDeterminator.ml | 6 +- infer/src/topl/Topl.ml | 2 +- infer/src/topl/ToplMonitor.ml | 11 +- infer/src/unit/DifferentialFiltersTests.ml | 4 +- infer/src/unit/DifferentialTestsUtils.ml | 11 +- infer/src/unit/FileDiffTests.ml | 10 +- infer/src/unit/JavaProfilerSamplesTest.ml | 4 +- infer/src/unit/TaintTests.ml | 3 +- infer/src/unit/abstractInterpreterTests.ml | 3 +- infer/src/unit/accessPathTests.ml | 11 +- infer/src/unit/addressTakenTests.ml | 3 +- infer/src/unit/analyzerTester.ml | 3 +- infer/src/unit/procCfgTests.ml | 5 +- infer/src/unit/weakTopologicalOrderTests.ml | 4 +- sledge/.ocamlformat | 3 +- sledge/src/control.ml | 4 +- sledge/src/domain/itv.ml | 3 +- sledge/src/domain/itv.mli | 1 + sledge/src/import/import.ml | 31 ++-- sledge/src/import/import.mli | 31 ++-- sledge/src/llair/exp.ml | 2 +- sledge/src/llair/term.ml | 2 +- sledge/src/llair/typ.mli | 6 +- sledge/src/sledge_buck.ml | 7 +- sledge/src/symbheap/exec.ml | 6 +- sledge/src/symbheap/solver.ml | 15 +- 289 files changed, 1526 insertions(+), 2119 deletions(-) diff --git a/Makefile b/Makefile index 49c375a25..7bad03c9e 100644 --- a/Makefile +++ b/Makefile @@ -221,7 +221,7 @@ DUNE_ML:=$(shell find * -name 'dune*.in' | grep -v workspace) fmt_dune: parallel $(OCAMLFORMAT_EXE) -i ::: $(DUNE_ML) -SRC_ML:=$(shell find * \( -name _build -or -name facebook-clang-plugins -or -path facebook/dependencies -or -path sledge/llvm \) -not -prune -or -type f -and -name '*'.ml -or -name '*'.mli 2>/dev/null) +SRC_ML:=$(shell find * \( -name _build -or -name facebook-clang-plugins -or -path facebook/dependencies -or -path sledge/llvm -or -path sledge/.llvm_build \) -not -prune -or -type f -and -name '*'.ml -or -name '*'.mli 2>/dev/null) .PHONY: fmt_all fmt_all: diff --git a/infer/src/.ocamlformat b/infer/src/.ocamlformat index c7e7d3a96..217e68c7a 100644 --- a/infer/src/.ocamlformat +++ b/infer/src/.ocamlformat @@ -1,4 +1,5 @@ profile = ocamlformat +break-before-in = fit-or-vertical let-binding-spacing = sparse margin = 100 -version = 0.9 +version = 0.12-20-gfce0d2e diff --git a/infer/src/IR/AccessPath.ml b/infer/src/IR/AccessPath.ml index 4ad8b78d8..92a78eb9f 100644 --- a/infer/src/IR/AccessPath.ml +++ b/infer/src/IR/AccessPath.ml @@ -14,7 +14,7 @@ module Raw = struct let compare_typ_ _ _ = 0 (* ignore types while comparing bases. we can't trust the types from all of our frontends to be - consistent, and the variable names should already be enough to distinguish the bases. *) + consistent, and the variable names should already be enough to distinguish the bases. *) type base = Var.t * typ_ [@@deriving compare] let equal_base = [%compare.equal: base] diff --git a/infer/src/IR/Annot.ml b/infer/src/IR/Annot.ml index 0544cb52a..3570dae9d 100644 --- a/infer/src/IR/Annot.ml +++ b/infer/src/IR/Annot.ml @@ -7,8 +7,8 @@ *) (** The Smallfoot Intermediate Language: Annotations *) -open! IStd +open! IStd module F = Format type parameter = {name: string option; value: string} [@@deriving compare] @@ -81,9 +81,7 @@ module Method = struct type t = {return: Item.t; params: Item.t list} (** Pretty print a method annotation. *) - let pp s fmt {return; params} = - F.fprintf fmt "%a %s(%a)" Item.pp return s (Pp.seq Item.pp) params - + let pp s fmt {return; params} = F.fprintf fmt "%a %s(%a)" Item.pp return s (Pp.seq Item.pp) params (** Empty method annotation. *) let empty = {return= []; params= []} diff --git a/infer/src/IR/Annot.mli b/infer/src/IR/Annot.mli index 7e8795c91..0b29e3ee6 100644 --- a/infer/src/IR/Annot.mli +++ b/infer/src/IR/Annot.mli @@ -7,8 +7,8 @@ *) (** The Smallfoot Intermediate Language: Annotations *) -open! IStd +open! IStd module F = Format type parameter = {name: string option; value: string} diff --git a/infer/src/IR/Attributes.ml b/infer/src/IR/Attributes.ml index 2f7b981b3..af752cf77 100644 --- a/infer/src/IR/Attributes.ml +++ b/infer/src/IR/Attributes.ml @@ -57,10 +57,9 @@ let should_try_to_update pname_blob akind = |> SqliteUtils.check_result_code db ~log:"replace bind pname" ; Sqlite3.bind find_stmt 2 (* :akind *) (Sqlite3.Data.INT (int64_of_attributes_kind akind)) |> SqliteUtils.check_result_code db ~log:"replace bind attribute kind" ; - SqliteUtils.result_single_column_option ~finalize:false ~log:"Attributes.replace" db - find_stmt + SqliteUtils.result_single_column_option ~finalize:false ~log:"Attributes.replace" db find_stmt |> (* there is no entry with a strictly larger "definedness" for that proc name *) - Option.is_none ) + Option.is_none ) let select_statement = diff --git a/infer/src/IR/Binop.ml b/infer/src/IR/Binop.ml index 831b5990b..cdafa5fde 100644 --- a/infer/src/IR/Binop.ml +++ b/infer/src/IR/Binop.ml @@ -7,6 +7,7 @@ *) (** The Smallfoot Intermediate Language: Binary Operators *) + open! IStd type ikind_option_for_binop = Typ.ikind option diff --git a/infer/src/IR/Binop.mli b/infer/src/IR/Binop.mli index 7984818f0..40b248e53 100644 --- a/infer/src/IR/Binop.mli +++ b/infer/src/IR/Binop.mli @@ -7,6 +7,7 @@ *) (** The Smallfoot Intermediate Language: Binary Operators *) + open! IStd (** Binary operations *) diff --git a/infer/src/IR/DecompiledExp.ml b/infer/src/IR/DecompiledExp.ml index 5aa7a4e49..9719a0518 100644 --- a/infer/src/IR/DecompiledExp.ml +++ b/infer/src/IR/DecompiledExp.ml @@ -68,7 +68,7 @@ let rec pp fmt = function F.fprintf fmt "*%a" pp de | Dfcall (fun_dexp, args, _, {cf_virtual= isvirtual}) -> let pp_args fmt des = - if eradicate_java () then ( if des <> [] then F.pp_print_string fmt "..." ) + if eradicate_java () then (if des <> [] then F.pp_print_string fmt "...") else Pp.comma_seq pp fmt des in let pp_fun fmt = function @@ -148,8 +148,7 @@ let pp_vpath pe fmt vpath = let rec has_tmp_var = function | Dpvar pvar | Dpvaraddr pvar -> Pvar.is_frontend_tmp pvar || Pvar.is_clang_tmp pvar - | Dderef dexp | Ddot (dexp, _) | Darrow (dexp, _) | Dunop (_, dexp) | Dsizeof (_, Some dexp, _) - -> + | Dderef dexp | Ddot (dexp, _) | Darrow (dexp, _) | Dunop (_, dexp) | Dsizeof (_, Some dexp, _) -> has_tmp_var dexp | Darray (dexp1, dexp2) | Dbinop (_, dexp1, dexp2) -> has_tmp_var dexp1 || has_tmp_var dexp2 diff --git a/infer/src/IR/Errlog.ml b/infer/src/IR/Errlog.ml index b6e80932a..0a674c0bb 100644 --- a/infer/src/IR/Errlog.ml +++ b/infer/src/IR/Errlog.ml @@ -29,11 +29,7 @@ let pp_loc_trace fmt l = PrettyPrintable.pp_collection ~pp_item:pp_loc_trace_ele let contains_exception loc_trace_elem = let pred nt = - match nt with - | Exception _ -> - true - | Condition _ | Procedure_start _ | Procedure_end _ -> - false + match nt with Exception _ -> true | Condition _ | Procedure_start _ | Procedure_end _ -> false in List.exists ~f:pred loc_trace_elem.lt_node_tags diff --git a/infer/src/IR/Exp.mli b/infer/src/IR/Exp.mli index 17b77bd93..37b2a81e4 100644 --- a/infer/src/IR/Exp.mli +++ b/infer/src/IR/Exp.mli @@ -47,14 +47,14 @@ and t = val equal : t -> t -> bool (** Equality for expressions. *) -(** Set of expressions. *) module Set : Caml.Set.S with type elt = t +(** Set of expressions. *) -(** Map with expression keys. *) module Map : Caml.Map.S with type key = t +(** Map with expression keys. *) -(** Hashtable with expression keys. *) module Hash : Caml.Hashtbl.S with type key = t +(** Hashtable with expression keys. *) val is_null_literal : t -> bool diff --git a/infer/src/IR/HilExp.ml b/infer/src/IR/HilExp.ml index 38f4caeda..b8daa6b56 100644 --- a/infer/src/IR/HilExp.ml +++ b/infer/src/IR/HilExp.ml @@ -382,7 +382,7 @@ let rec get_typ tenv = function Some (Typ.mk (Typ.Tint Typ.IBool)) | BinaryOperator (_, e1, e2) -> ( (* TODO: doing this properly will require taking account of language-specific coercion - semantics. Only return a type when the operands have the same type for now *) + semantics. Only return a type when the operands have the same type for now *) match (get_typ tenv e1, get_typ tenv e2) with | Some typ1, Some typ2 when Typ.equal typ1 typ2 -> Some typ1 @@ -572,9 +572,9 @@ and of_sil ~include_array_indexes ~f_resolve_id ~add_deref exp typ = typ ) | Lindex (Const (Cstr s), index_exp) -> (* indexed string literal (e.g., "foo"[1]). represent this by introducing a dummy variable - for the string literal. if you actually need to see the value of the string literal in the - analysis, you should probably be using SIL. this is unsound if the code modifies the - literal, e.g. using `const_cast` *) + for the string literal. if you actually need to see the value of the string literal in the + analysis, you should probably be using SIL. this is unsound if the code modifies the + literal, e.g. using `const_cast` *) of_sil_ (Exp.Lindex (Var (Ident.create_normal (Ident.string_to_name s) 0), index_exp)) typ | Lindex (root_exp, index_exp) -> ( match access_expr_of_lhs_exp ~include_array_indexes ~f_resolve_id ~add_deref exp typ with @@ -679,9 +679,9 @@ let access_expr_of_exp ~include_array_indexes ~f_resolve_id exp typ = Some access_expr | BinaryOperator (_, exp0, exp1) -> ( (* pointer arithmetic. somewhere in one of the expressions, there should be at least - one pointer type represented as an access path. just use that access path and forget - about the arithmetic. if you need to model this more precisely, you should be using - SIL instead *) + one pointer type represented as an access path. just use that access path and forget + about the arithmetic. if you need to model this more precisely, you should be using + SIL instead *) match get_access_exprs exp0 with | ap :: _ -> Some ap @@ -689,7 +689,7 @@ let access_expr_of_exp ~include_array_indexes ~f_resolve_id exp typ = match get_access_exprs exp1 with ap :: _ -> Some ap | [] -> None ) ) | Constant (Const.Cint i) -> (* this can happen in intentionally crashing code like *0xdeadbeef = 0 used for - debugging. doesn't really matter what we do here, so just create a dummy var *) + debugging. doesn't really matter what we do here, so just create a dummy var *) let dummy_base_var = Var.of_id (Ident.create_normal (Ident.string_to_name (IntLit.to_string i)) 0) in diff --git a/infer/src/IR/HilInstr.ml b/infer/src/IR/HilInstr.ml index 542d8e704..256005227 100644 --- a/infer/src/IR/HilInstr.ml +++ b/infer/src/IR/HilInstr.ml @@ -27,8 +27,8 @@ type t = let pp fmt = function | Assign (access_expr, exp, loc) -> - F.fprintf fmt "%a := %a [%a]" HilExp.AccessExpression.pp access_expr HilExp.pp exp - Location.pp loc + F.fprintf fmt "%a := %a [%a]" HilExp.AccessExpression.pp access_expr HilExp.pp exp Location.pp + loc | Assume (exp, _, _, loc) -> F.fprintf fmt "assume %a [%a]" HilExp.pp exp Location.pp loc | Call (ret, call, actuals, _, loc) -> @@ -60,8 +60,8 @@ let of_sil ~include_array_indexes ~f_resolve_id (instr : Sil.instr) = match instr with | Load {id= lhs_id; e= rhs_exp; typ= rhs_typ; loc} -> analyze_id_assignment ~add_deref:true (Var.of_id lhs_id) rhs_exp rhs_typ loc - | Store {e1= Lvar lhs_pvar; typ= lhs_typ; e2= rhs_exp; loc} - when Pvar.is_ssa_frontend_tmp lhs_pvar -> + | Store {e1= Lvar lhs_pvar; typ= lhs_typ; e2= rhs_exp; loc} when Pvar.is_ssa_frontend_tmp lhs_pvar + -> (* do not need to add deref here as it is added implicitly in of_pvar by forgetting the & *) analyze_id_assignment (Var.of_pvar lhs_pvar) rhs_exp lhs_typ loc | Call diff --git a/infer/src/IR/Ident.ml b/infer/src/IR/Ident.ml index ad4ef75ab..08f57e290 100644 --- a/infer/src/IR/Ident.ml +++ b/infer/src/IR/Ident.ml @@ -217,9 +217,7 @@ let update_name_generator ids = (** Generate a normal identifier whose name encodes a path given as a string. *) -let create_path pathstring = - create_normal (string_to_name ("%path%" ^ pathstring)) path_ident_stamp - +let create_path pathstring = create_normal (string_to_name ("%path%" ^ pathstring)) path_ident_stamp (** {2 Pretty Printing} *) diff --git a/infer/src/IR/Ident.mli b/infer/src/IR/Ident.mli index b288ea945..189b342a3 100644 --- a/infer/src/IR/Ident.mli +++ b/infer/src/IR/Ident.mli @@ -28,14 +28,14 @@ type kind [@@deriving compare] val equal_kind : kind -> kind -> bool (** Equality for kind. *) -(** Set for identifiers. *) module Set : Caml.Set.S with type elt = t +(** Set for identifiers. *) -(** Hash table with ident as key. *) module Hash : Caml.Hashtbl.S with type key = t +(** Hash table with ident as key. *) -(** Map with ident as key. *) module Map : Caml.Map.S with type key = t +(** Map with ident as key. *) module HashQueue : Hash_queue.S with type Key.t = t diff --git a/infer/src/IR/Localise.ml b/infer/src/IR/Localise.ml index e9961e352..b5ef77cf9 100644 --- a/infer/src/IR/Localise.ml +++ b/infer/src/IR/Localise.ml @@ -328,8 +328,8 @@ let desc_unsafe_guarded_by_access accessed_fld guarded_by_str loc = Format.asprintf "The field %a is annotated with %a, but the lock %a is not held during the access to the \ field %s. Since the current method is non-private, it can be called from outside the \ - current class without synchronization. Consider wrapping the access in a %s block or \ - making the method private." + current class without synchronization. Consider wrapping the access in a %s block or making \ + the method private." MF.pp_monospaced accessed_fld_str MF.pp_monospaced annot_str MF.pp_monospaced guarded_by_str line_info syncronized_str in @@ -469,8 +469,7 @@ let desc_allocation_mismatch alloc dealloc = let using (primitive_pname, called_pname, loc) = let by_call = if Typ.Procname.equal primitive_pname called_pname then "" - else - " by call to " ^ MF.monospaced_to_string (Typ.Procname.to_simplified_string called_pname) + else " by call to " ^ MF.monospaced_to_string (Typ.Procname.to_simplified_string called_pname) in "using " ^ MF.monospaced_to_string (Typ.Procname.to_simplified_string primitive_pname) @@ -564,7 +563,7 @@ let desc_frontend_warning desc sugg_opt loc = let tags = Tags.create () in let sugg = match sugg_opt with Some sugg -> sugg | None -> "" in (* If the description ends in a period, we remove it because the sentence continues with - "at line ..." *) + "at line ..." *) let desc = match String.chop_suffix ~suffix:"." desc with Some desc -> desc | None -> desc in let description = Format.sprintf "%s %s. %s" desc (at_line tags loc) sugg in {no_desc with descriptions= [description]; tags= !tags} @@ -658,8 +657,7 @@ let desc_retain_cycle cycle_str loc cycle_dotty = Logging.d_strln "Proposition with retain cycle:" ; let tags = Tags.create () in let desc = - Format.sprintf "Retain cycle %s involving the following objects:%s" (at_line tags loc) - cycle_str + Format.sprintf "Retain cycle %s involving the following objects:%s" (at_line tags loc) cycle_str in {descriptions= [desc]; tags= !tags; dotty= cycle_dotty} diff --git a/infer/src/IR/Mangled.mli b/infer/src/IR/Mangled.mli index 994657d6a..fcf27a02c 100644 --- a/infer/src/IR/Mangled.mli +++ b/infer/src/IR/Mangled.mli @@ -42,8 +42,8 @@ val is_self : t -> bool val rename : f:(string -> string) -> t -> t (** Maps over both the plain and the mangled components. *) -(** Set of Mangled. *) module Set : Caml.Set.S with type elt = t +(** Set of Mangled. *) -(** Map with Mangled as key *) module Map : Caml.Map.S with type key = t +(** Map with Mangled as key *) diff --git a/infer/src/IR/Objc_models.ml b/infer/src/IR/Objc_models.ml index 047fd865d..c5a19df54 100644 --- a/infer/src/IR/Objc_models.ml +++ b/infer/src/IR/Objc_models.ml @@ -167,11 +167,7 @@ module Core_foundation_model = struct type core_lib = Core_foundation | Core_graphics let core_lib_to_type_list lib = - match lib with - | Core_foundation -> - core_foundation_types - | Core_graphics -> - core_graphics_types + match lib with Core_foundation -> core_foundation_types | Core_graphics -> core_graphics_types let rec is_core_lib lib typ = diff --git a/infer/src/IR/Procdesc.ml b/infer/src/IR/Procdesc.ml index c5a4f8f85..79898d43a 100644 --- a/infer/src/IR/Procdesc.ml +++ b/infer/src/IR/Procdesc.ml @@ -17,9 +17,7 @@ module NodeKey = struct let to_string = Caml.Digest.to_hex let compute node ~simple_key ~succs ~preds = - let v = - (simple_key node, List.rev_map ~f:simple_key succs, List.rev_map ~f:simple_key preds) - in + let v = (simple_key node, List.rev_map ~f:simple_key succs, List.rev_map ~f:simple_key preds) in Utils.better_hash v @@ -351,11 +349,7 @@ module Node = struct let pp_instrs ~highlight pe0 f node = let pe = - match highlight with - | None -> - pe0 - | Some instr -> - Pp.extend_colormap pe0 (Obj.repr instr) Red + match highlight with None -> pe0 | Some instr -> Pp.extend_colormap pe0 (Obj.repr instr) Red in Instrs.pp pe f (get_instrs node) @@ -428,17 +422,17 @@ end (* =============== END of module Node =============== *) -(** Map over nodes *) module NodeMap = Caml.Map.Make (Node) +(** Map over nodes *) -(** Hash table with nodes as keys. *) module NodeHash = Hashtbl.Make (Node) +(** Hash table with nodes as keys. *) -(** Set of nodes. *) module NodeSet = Node.NodeSet +(** Set of nodes. *) -(** Map with node id keys. *) module IdMap = Node.IdMap +(** Map with node id keys. *) (** procedure description *) type t = @@ -594,9 +588,7 @@ let set_exit_node pdesc node = pdesc.exit_node <- node let set_start_node pdesc node = pdesc.start_node <- node (** Append the locals to the list of local variables *) -let append_locals pdesc new_locals = - pdesc.attributes.locals <- pdesc.attributes.locals @ new_locals - +let append_locals pdesc new_locals = pdesc.attributes.locals <- pdesc.attributes.locals @ new_locals let set_succs_exn_only (node : Node.t) exn = node.exn <- exn @@ -837,10 +829,10 @@ let is_connected proc_desc = if List.is_empty succs || List.is_empty preds then Error `Other else Ok () | Node.Join_node -> (* Join node has the exception that it may be without predecessors - and pointing to between_join_and_exit which points to an exit node. - This happens when the if branches end with a return. - Nested if statements, where all branches have return statements, - introduce a sequence of join nodes *) + and pointing to between_join_and_exit which points to an exit node. + This happens when the if branches end with a return. + Nested if statements, where all branches have return statements, + introduce a sequence of join nodes *) if (List.is_empty preds && not (is_consecutive_join_nodes n NodeSet.empty)) || ((not (List.is_empty preds)) && List.is_empty succs) diff --git a/infer/src/IR/Procdesc.mli b/infer/src/IR/Procdesc.mli index 85d457482..0ff0d3c6c 100644 --- a/infer/src/IR/Procdesc.mli +++ b/infer/src/IR/Procdesc.mli @@ -178,17 +178,17 @@ module Node : sig val compute_key : t -> NodeKey.t end -(** Map with node id keys. *) module IdMap : PrettyPrintable.PPMap with type key = Node.id +(** Map with node id keys. *) -(** Hash table with nodes as keys. *) module NodeHash : Caml.Hashtbl.S with type key = Node.t +(** Hash table with nodes as keys. *) -(** Map over nodes. *) module NodeMap : Caml.Map.S with type key = Node.t +(** Map over nodes. *) -(** Set of nodes. *) module NodeSet : Caml.Set.S with type elt = Node.t +(** Set of nodes. *) (** procedure descriptions *) @@ -316,8 +316,8 @@ val has_modify_in_block_attr : t -> Pvar.t -> bool val is_connected : t -> (unit, [`Join | `Other]) Result.t (** checks whether a cfg for the given procdesc is connected or not *) +module SQLite : SqliteUtils.Data with type t = t option (** per-procedure CFGs are stored in the SQLite "procedures" table as NULL if the procedure has no CFG *) -module SQLite : SqliteUtils.Data with type t = t option val load : Typ.Procname.t -> t option diff --git a/infer/src/IR/ProcnameDispatcher.ml b/infer/src/IR/ProcnameDispatcher.ml index 04f5e2f13..da71d7f38 100644 --- a/infer/src/IR/ProcnameDispatcher.ml +++ b/infer/src/IR/ProcnameDispatcher.ml @@ -106,7 +106,7 @@ type ( 'context type ('context, 'f_in, 'f_out, 'captured_types, 'emptyness) path_extra = | PathEmpty : ('context, 'f, 'f, unit, empty) path_extra | PathNonEmpty : - { on_objc_cpp: 'context -> 'f_in -> objc_cpp -> ('f_out * 'captured_types capt) option } + {on_objc_cpp: 'context -> 'f_in -> objc_cpp -> ('f_out * 'captured_types capt) option} -> ('context, 'f_in, 'f_out, 'captured_types, non_empty) path_extra type ('context, 'f_in, 'f_out, 'captured_types, 'markers_in, 'markers_out, 'emptyness) path_matcher = @@ -272,14 +272,8 @@ let templ_cons : let templ_end : ('context, 'f_in, 'f_out, 'captured_types, 'markers_in, 'markers_out, _) templ_matcher - -> ( 'context - , 'f_in - , 'f_out - , 'captured_types - , 'markers_in - , 'markers_out - , non_empty ) - path_matcher = + -> ('context, 'f_in, 'f_out, 'captured_types, 'markers_in, 'markers_out, non_empty) path_matcher + = let match_empty_templ_args (f, captured_types, template_args) = match template_args with [] -> Some (f, captured_types) | _ -> None in @@ -544,8 +538,7 @@ module Call = struct | Exp.Var v -> v | e -> - Logging.(die InternalError) - "Expected Lvar, got %a:%a" Exp.pp e (Typ.pp Pp.text) (typ arg) + Logging.(die InternalError) "Expected Lvar, got %a:%a" Exp.pp e (Typ.pp Pp.text) (typ arg) end type ('context, 'f_in, 'f_out, 'captured_types) proc_matcher = @@ -767,16 +760,15 @@ module Call = struct (** Matches third captured type *) let match_typ3 : - 'marker -> ('context, _ * (_ * ('marker mtyp * _)), _ * (_ * ('marker * _))) one_arg_matcher - = + 'marker -> ('context, _ * (_ * ('marker mtyp * _)), _ * (_ * ('marker * _))) one_arg_matcher = let pos3 (_, (_, (x, _))) = x in fun marker -> mk_match_typ_nth pos3 pos3 marker (** Matches the type matched by the given path_matcher *) let match_typ : - ('context, _, _, unit, unit, unit, non_empty) path_matcher - -> ('context, _, _) one_arg_matcher = + ('context, _, _, unit, unit, unit, non_empty) path_matcher -> ('context, _, _) one_arg_matcher + = fun m -> let ({on_templated_name} : (_, _, _, unit, unit, unit, non_empty) path_matcher) = m in let rec match_typ context typ = diff --git a/infer/src/IR/ProcnameDispatcher.mli b/infer/src/IR/ProcnameDispatcher.mli index de9c4e660..393d1d00c 100644 --- a/infer/src/IR/ProcnameDispatcher.mli +++ b/infer/src/IR/ProcnameDispatcher.mli @@ -9,7 +9,8 @@ open! IStd (** To be used in 'list_constraint *) type accept_more - and end_of_list + +and end_of_list (* Markers are a fool-proofing mechanism to avoid mistaking captured types. Template argument types can be captured with [capt_typ] to be referenced later @@ -226,7 +227,8 @@ module Call : sig include Common - with type ('context, 'f) dispatcher = 'context -> Typ.Procname.t -> FuncArg.t list -> 'f option + with type ('context, 'f) dispatcher = + 'context -> Typ.Procname.t -> FuncArg.t list -> 'f option val merge_dispatchers : ('context, 'f) dispatcher -> ('context, 'f) dispatcher -> ('context, 'f) dispatcher diff --git a/infer/src/IR/Pvar.ml b/infer/src/IR/Pvar.ml index af9cac6a4..cdb726a9f 100644 --- a/infer/src/IR/Pvar.ml +++ b/infer/src/IR/Pvar.ml @@ -38,8 +38,7 @@ type t = {pv_hash: int; pv_name: Mangled.t; pv_kind: pvar_kind} [@@deriving comp let get_name_of_local_with_procname var = match var.pv_kind with | Local_var pname -> - Mangled.from_string - (F.asprintf "%s_%a" (Mangled.to_string var.pv_name) Typ.Procname.pp pname) + Mangled.from_string (F.asprintf "%s_%a" (Mangled.to_string var.pv_name) Typ.Procname.pp pname) | _ -> var.pv_name @@ -124,9 +123,7 @@ let materialized_cpp_temporary = "SIL_materialize_temp__" let is_frontend_tmp pvar = (* Check whether the program variable is a temporary one generated by Sawja, javac, or some other bytecode/name generation pass. valid java identifiers cannot contain `$` *) - let is_bytecode_tmp name = - String.contains name '$' || String.is_prefix ~prefix:"CatchVar" name - in + let is_bytecode_tmp name = String.contains name '$' || String.is_prefix ~prefix:"CatchVar" name in (* Check whether the program variable is generated by [mk_tmp] *) let is_sil_tmp name = String.is_prefix ~prefix:tmp_prefix name in let name = to_string pvar in diff --git a/infer/src/IR/Sil.ml b/infer/src/IR/Sil.ml index 9e129e5d1..fce95875d 100644 --- a/infer/src/IR/Sil.ml +++ b/infer/src/IR/Sil.ml @@ -218,12 +218,7 @@ let compare_hpara_dll = compare_hpara_dll0 (fun _ _ -> 0) let equal_hpara_dll = [%compare.equal: hpara_dll] (** {2 Comparision and Inspection Functions} *) -let is_objc_object = function - | Hpointsto (_, _, Sizeof {typ}) -> - Typ.is_objc_class typ - | _ -> - false - +let is_objc_object = function Hpointsto (_, _, Sizeof {typ}) -> Typ.is_objc_class typ | _ -> false (** Check if a pvar is a local static in objc *) let is_static_local_name pname pvar = @@ -301,8 +296,7 @@ let pp_texp pe f = function | Exp.Sizeof {typ; nbytes; dynamic_length; subtype} -> let pp_len f l = Option.iter ~f:(F.fprintf f "[%a]" (pp_exp_printenv pe)) l in let pp_size f size = Option.iter ~f:(Int.pp f) size in - F.fprintf f "%a%a%a%a" (Typ.pp pe) typ pp_size nbytes pp_len dynamic_length Subtype.pp - subtype + F.fprintf f "%a%a%a%a" (Typ.pp pe) typ pp_size nbytes pp_len dynamic_length Subtype.pp subtype | e -> pp_exp_printenv pe f e @@ -827,9 +821,7 @@ let rec pp_sexp_env pe0 envo f se = | Eexp (e, inst) -> F.fprintf f "%a%a" (pp_exp_printenv pe) e (pp_inst_if_trace pe) inst | Estruct (fel, inst) -> - let pp_diff f (n, se) = - F.fprintf f "%a:%a" Typ.Fieldname.pp n (pp_sexp_env pe envo) se - in + let pp_diff f (n, se) = F.fprintf f "%a:%a" Typ.Fieldname.pp n (pp_sexp_env pe envo) se in F.fprintf f "{%a}%a" (pp_seq_diff pp_diff pe) fel (pp_inst_if_trace pe) inst | Earray (len, nel, inst) -> let pp_diff f (i, se) = @@ -1268,8 +1260,7 @@ let rec exp_sub_ids (f : subst_fun) exp = let apply_sub subst : subst_fun = - fun id -> - match List.Assoc.find subst ~equal:Ident.equal id with Some x -> x | None -> Exp.Var id + fun id -> match List.Assoc.find subst ~equal:Ident.equal id with Some x -> x | None -> Exp.Var id let exp_sub (subst : subst) e = exp_sub_ids (apply_sub subst) e @@ -1305,8 +1296,7 @@ let instr_sub_ids ~sub_id_binders f instr = if phys_equal actual' actual then actual_pair else (actual', typ) ) actuals in - if - phys_equal ret_id' ret_id_typ && phys_equal fun_exp' fun_exp && phys_equal actuals' actuals + if phys_equal ret_id' ret_id_typ && phys_equal fun_exp' fun_exp && phys_equal actuals' actuals then instr else Call (ret_id', fun_exp', actuals', call_flags, loc) | Prune (exp, loc, true_branch, if_kind) -> @@ -1464,14 +1454,8 @@ let hpred_compact sh hpred = let exp_get_offsets exp = let rec f offlist_past e = match (e : Exp.t) with - | Var _ - | Const _ - | UnOp _ - | BinOp _ - | Exn _ - | Closure _ - | Lvar _ - | Sizeof {dynamic_length= None} -> + | Var _ | Const _ | UnOp _ | BinOp _ | Exn _ | Closure _ | Lvar _ | Sizeof {dynamic_length= None} + -> offlist_past | Sizeof {dynamic_length= Some l} -> f offlist_past l diff --git a/infer/src/IR/Sil.mli b/infer/src/IR/Sil.mli index 8879ce043..3e15063a8 100644 --- a/infer/src/IR/Sil.mli +++ b/infer/src/IR/Sil.mli @@ -7,8 +7,8 @@ *) (** The Smallfoot Intermediate Language *) -open! IStd +open! IStd module F = Format (** {2 Programs and Types} *) @@ -239,8 +239,8 @@ val equal_hpred : ?inst:bool -> hpred -> hpred -> bool The inst:: parameter specifies whether instumentations should also be considered (false by default). *) -(** Sets of heap predicates *) module HpredSet : Caml.Set.S with type elt = hpred +(** Sets of heap predicates *) (** {2 Compaction} *) diff --git a/infer/src/IR/SourceFiles.ml b/infer/src/IR/SourceFiles.ml index d0b8ceb67..c9b866827 100644 --- a/infer/src/IR/SourceFiles.ml +++ b/infer/src/IR/SourceFiles.ml @@ -109,9 +109,7 @@ let is_captured source = |> Option.is_some ) -let is_non_empty_statement = - ResultsDatabase.register_statement "SELECT 1 FROM source_files LIMIT 1" - +let is_non_empty_statement = ResultsDatabase.register_statement "SELECT 1 FROM source_files LIMIT 1" let is_empty () = ResultsDatabase.with_registered_statement is_non_empty_statement ~f:(fun db stmt -> @@ -134,8 +132,8 @@ let is_freshly_captured source = SourceFile.SQLite.serialize source |> Sqlite3.bind load_stmt 1 |> SqliteUtils.check_result_code db ~log:"load bind source file" ; - SqliteUtils.result_single_column_option ~finalize:false - ~log:"SourceFiles.is_freshly_captured" db load_stmt + SqliteUtils.result_single_column_option ~finalize:false ~log:"SourceFiles.is_freshly_captured" + db load_stmt |> Option.value_map ~default:false ~f:deserialize_freshly_captured ) diff --git a/infer/src/IR/SpecializeProcdesc.ml b/infer/src/IR/SpecializeProcdesc.ml index 5ead46b0a..787636895 100644 --- a/infer/src/IR/SpecializeProcdesc.ml +++ b/infer/src/IR/SpecializeProcdesc.ml @@ -261,9 +261,7 @@ let with_block_args_instrs resolved_pdesc substitutions = in let call_instr = let id_exps = List.map ~f:(fun (id, _, typ) -> (id, typ)) id_exp_typs in - let converted_args = - List.map ~f:(fun (exp, typ) -> (convert_exp exp, typ)) origin_args - in + let converted_args = List.map ~f:(fun (exp, typ) -> (convert_exp exp, typ)) origin_args in Sil.Call ( return_ids , Exp.Const (Const.Cfun block_name) @@ -299,7 +297,7 @@ let append_no_duplicates_formals_and_annot = let with_block_args callee_pdesc pname_with_block_args block_args = let callee_attributes = Procdesc.get_attributes callee_pdesc in (* Substitution from a block parameter to the block name and the new formals - that correspond to the captured variables *) + that correspond to the captured variables *) let substitutions : (Typ.Procname.t * (Mangled.t * Typ.t) list) Mangled.Map.t = List.fold2_exn callee_attributes.formals block_args ~init:Mangled.Map.empty ~f:(fun subts (param_name, _) block_arg_opt -> @@ -309,7 +307,7 @@ let with_block_args callee_pdesc pname_with_block_args block_args = List.map ~f:(fun (_, var, typ) -> (* Here we create fresh names for the new formals, based on the names of the captured - variables annotated with the name of the caller method *) + variables annotated with the name of the caller method *) (Pvar.get_name_of_local_with_procname var, typ) ) cl.captured_vars in @@ -318,7 +316,7 @@ let with_block_args callee_pdesc pname_with_block_args block_args = subts ) in (* Extend formals with fresh variables for the captured variables of the block arguments, - without duplications. *) + without duplications. *) let new_formals_blocks_captured_vars, extended_formals_annots = let new_formals_blocks_captured_vars_with_annots = let formals_annots = @@ -341,8 +339,8 @@ let with_block_args callee_pdesc pname_with_block_args block_args = source_file | None -> Logging.die InternalError - "specialize_with_block_args ahould only be called with defined procedures, but we \ - cannot find the captured file of procname %a" + "specialize_with_block_args ahould only be called with defined procedures, but we cannot \ + find the captured file of procname %a" Typ.Procname.pp pname in let resolved_attributes = diff --git a/infer/src/IR/Tenv.ml b/infer/src/IR/Tenv.ml index 887f03432..109766225 100644 --- a/infer/src/IR/Tenv.ml +++ b/infer/src/IR/Tenv.ml @@ -9,8 +9,8 @@ module L = Logging (** Module for Type Environments. *) -(** Hash tables on type names. *) module TypenameHash = Caml.Hashtbl.Make (Typ.Name) +(** Hash tables on type names. *) module TypenameHashNormalizer = MaximumSharing.ForHashtbl (TypenameHash) diff --git a/infer/src/IR/Typ.ml b/infer/src/IR/Typ.ml index 48877cc23..0e1e3f706 100644 --- a/infer/src/IR/Typ.ml +++ b/infer/src/IR/Typ.ml @@ -129,10 +129,7 @@ let range_of_ikind = let ikind_is_char = function IChar | ISChar | IUChar -> true | _ -> false (** Kinds of floating-point numbers *) -type fkind = - | FFloat (** [float] *) - | FDouble (** [double] *) - | FLongDouble (** [long double] *) +type fkind = FFloat (** [float] *) | FDouble (** [double] *) | FLongDouble (** [long double] *) [@@deriving compare] let equal_fkind = [%compare.equal: fkind] @@ -684,8 +681,8 @@ module Procname = struct match verbosity with | Verbose | Non_verbose -> (* if verbose, then package.class.method(params): rtype, - else rtype package.class.method(params) - verbose is used for example to create unique filenames, non_verbose to create reports *) + else rtype package.class.method(params) + verbose is used for example to create unique filenames, non_verbose to create reports *) let pp_class_name verbosity fmt j = pp_type_verbosity verbosity fmt (Name.Java.split_typename j.class_name) in @@ -1423,8 +1420,7 @@ module Procname = struct end module Fieldname = struct - type t = Clang of {class_name: Name.t; field_name: string} | Java of string - [@@deriving compare] + type t = Clang of {class_name: Name.t; field_name: string} | Java of string [@@deriving compare] let equal = [%compare.equal: t] diff --git a/infer/src/IR/Typ.mli b/infer/src/IR/Typ.mli index 6b0a08766..f4f018421 100644 --- a/infer/src/IR/Typ.mli +++ b/infer/src/IR/Typ.mli @@ -55,10 +55,7 @@ val ikind_is_unsigned : ikind -> bool (** Check whether the integer kind is unsigned *) (** Kinds of floating-point numbers *) -type fkind = - | FFloat (** [float] *) - | FDouble (** [double] *) - | FLongDouble (** [long double] *) +type fkind = FFloat (** [float] *) | FDouble (** [double] *) | FLongDouble (** [long double] *) [@@deriving compare] (** kind of pointer *) @@ -448,8 +445,7 @@ being the name of the struct, [None] means the parameter is of some other type. ; template_args: template_spec_info } [@@deriving compare] - val make : - Name.t -> string -> kind -> template_spec_info -> Parameter.clang_parameter list -> t + val make : Name.t -> string -> kind -> template_spec_info -> Parameter.clang_parameter list -> t (** Create an objc procedure name from a class_name and method_name. *) val get_class_name : t -> string @@ -540,14 +536,14 @@ being the name of the struct, [None] means the parameter is of some other type. val is_objc_method : t -> bool - (** Hash tables with proc names as keys. *) module Hash : Caml.Hashtbl.S with type key = t + (** Hash tables with proc names as keys. *) - (** Maps from proc names. *) module Map : PrettyPrintable.PPMap with type key = t + (** Maps from proc names. *) - (** Sets of proc names. *) module Set : PrettyPrintable.PPSet with type elt = t + (** Sets of proc names. *) module SQLite : sig val serialize : t -> Sqlite3.Data.t @@ -643,11 +639,11 @@ module Fieldname : sig val equal : t -> t -> bool (** Equality for field names. *) - (** Set for fieldnames *) module Set : Caml.Set.S with type elt = t + (** Set for fieldnames *) - (** Map for fieldnames *) module Map : Caml.Map.S with type key = t + (** Map for fieldnames *) module Clang : sig val from_class_name : Name.t -> string -> t diff --git a/infer/src/IR/WeakTopologicalOrder.ml b/infer/src/IR/WeakTopologicalOrder.ml index f4c8b6440..72290bb87 100644 --- a/infer/src/IR/WeakTopologicalOrder.ml +++ b/infer/src/IR/WeakTopologicalOrder.ml @@ -60,10 +60,10 @@ module Partition = struct match fold_right head ~init ~f:prepend_node with | Empty | Component _ -> (* [fold_right] is expected to always provide a non-empty sequence. - Hence the result of [fold_right ~f:prepend_node] will always start with a Node. *) + Hence the result of [fold_right ~f:prepend_node] will always start with a Node. *) Logging.(die InternalError) - "WeakTopologicalOrder.Partition.expand: the expansion function fold_right should \ - not return ~init directly" + "WeakTopologicalOrder.Partition.expand: the expansion function fold_right should not \ + return ~init directly" | Node {node= head; next= rest} -> Component {head; rest; next} ) @@ -111,12 +111,12 @@ module type Make = functor (CFG : PreProcCfg) -> S with module CFG = CFG module Bourdoncle_SCC (CFG : PreProcCfg) = struct module CFG = CFG + module Dfn = CFG.Node.IdMap (** [dfn] contains a DFS pre-order indexing. A node is not in the map if it has never been visited. A node's dfn is +oo if it has been fully visited (head of cross-edges) or we want to hide it for building a subcomponent partition (head of highest back-edges). *) - module Dfn = CFG.Node.IdMap (* Unlike Bourdoncle's paper version or OCamlGraph implementation, this implementation handles diff --git a/infer/src/IR/WeakTopologicalOrder.mli b/infer/src/IR/WeakTopologicalOrder.mli index 6f7dc70e2..33020eda5 100644 --- a/infer/src/IR/WeakTopologicalOrder.mli +++ b/infer/src/IR/WeakTopologicalOrder.mli @@ -78,8 +78,8 @@ end module type Make = functor (CFG : PreProcCfg) -> S with module CFG = CFG +module Bourdoncle_SCC : Make (** Implementation of Bourdoncle's "Hierarchical decomposition of a directed graph into strongly connected components and subcomponents". See [Bou] Figure 4, page 10. *) -module Bourdoncle_SCC : Make diff --git a/infer/src/absint/AbstractDomain.ml b/infer/src/absint/AbstractDomain.ml index 1c6e5219d..98ca10512 100644 --- a/infer/src/absint/AbstractDomain.ml +++ b/infer/src/absint/AbstractDomain.ml @@ -532,8 +532,7 @@ module InvertedMap (Key : PrettyPrintable.PrintableOrderedType) (ValueDomain : S inter prev next ~f:(fun prev next -> ValueDomain.widen ~prev ~next ~num_iters) end -module SafeInvertedMap (Key : PrettyPrintable.PrintableOrderedType) (ValueDomain : WithTop) = -struct +module SafeInvertedMap (Key : PrettyPrintable.PrintableOrderedType) (ValueDomain : WithTop) = struct module M = InvertedMap (Key) (ValueDomain) type key = M.key diff --git a/infer/src/absint/AbstractDomain.mli b/infer/src/absint/AbstractDomain.mli index da4003043..2effa2b0c 100644 --- a/infer/src/absint/AbstractDomain.mli +++ b/infer/src/absint/AbstractDomain.mli @@ -17,9 +17,9 @@ end open! Types +exception Stop_analysis (** This exception can be raised by abstract interpreters to stop the analysis early without triggering further errors. Clients who raise this exception should catch it eventually. *) -exception Stop_analysis (** Abstract domains and domain combinators *) @@ -38,13 +38,12 @@ module type S = sig val widen : prev:t -> next:t -> num_iters:int -> t end -include - (* ocaml ignores the warning suppression at toplevel, hence the [include struct ... end] trick *) +include (* ocaml ignores the warning suppression at toplevel, hence the [include struct ... end] trick *) sig - [@@@warning "-60"] + [@@@warning "-60"] - (** a trivial domain *) - module Empty : S with type t = unit + module Empty : S with type t = unit + (** a trivial domain *) end (** A domain with an explicit bottom value *) @@ -95,12 +94,11 @@ module Flat (V : PrettyPrintable.PrintableEquatableType) : sig val get : t -> V.t option end -include - sig - [@@@warning "-60"] +include sig + [@@@warning "-60"] - (** Stacked abstract domain: tagged union of [Below] and [Above] domains where all elements of [Below] are strictly smaller than elements of [Above] *) - module Stacked (Below : S) (Above : S) : S with type t = (Below.t, Above.t) below_above + (** Stacked abstract domain: tagged union of [Below] and [Above] domains where all elements of [Below] are strictly smaller than elements of [Above] *) + module Stacked (Below : S) (Above : S) : S with type t = (Below.t, Above.t) below_above end module StackedUtils : sig @@ -165,13 +163,12 @@ module type FiniteSetS = sig include WithBottom with type t := t end -include - sig - [@@@warning "-60"] +include sig + [@@@warning "-60"] - (** Lift a PPSet to a powerset domain ordered by subset. The elements of the set should be drawn from + (** Lift a PPSet to a powerset domain ordered by subset. The elements of the set should be drawn from a *finite* collection of possible values, since the widening operator here is just union. *) - module FiniteSetOfPPSet (PPSet : PrettyPrintable.PPSet) : FiniteSetS with type elt = PPSet.elt + module FiniteSetOfPPSet (PPSet : PrettyPrintable.PPSet) : FiniteSetS with type elt = PPSet.elt end (** Lift a set to a powerset domain ordered by subset. The elements of the set should be drawn from @@ -195,18 +192,14 @@ module type MapS = sig include WithBottom with type t := t end -include - sig - [@@@warning "-60"] +include sig + [@@@warning "-60"] - (** Map domain ordered by union over the set of bindings, so the bottom element is the empty map. + (** Map domain ordered by union over the set of bindings, so the bottom element is the empty map. Every element implicitly maps to bottom unless it is explicitly bound to something else. Uses PPMap as the underlying map *) - module MapOfPPMap (PPMap : PrettyPrintable.PPMap) (ValueDomain : S) : - MapS - with type key = PPMap.key - and type value = ValueDomain.t - and type t = ValueDomain.t PPMap.t + module MapOfPPMap (PPMap : PrettyPrintable.PPMap) (ValueDomain : S) : + MapS with type key = PPMap.key and type value = ValueDomain.t and type t = ValueDomain.t PPMap.t end (** Map domain ordered by union over the set of bindings, so the bottom element is the empty map. @@ -233,30 +226,29 @@ module SafeInvertedMap (Key : PrettyPrintable.PrintableOrderedType) (ValueDomain (* ocaml ignores the warning suppression at toplevel, hence the [include struct ... end] trick *) -include - sig - [@@@warning "-60"] +include sig + [@@@warning "-60"] - module FiniteMultiMap - (Key : PrettyPrintable.PrintableOrderedType) - (Value : PrettyPrintable.PrintableOrderedType) : sig - include WithBottom + module FiniteMultiMap + (Key : PrettyPrintable.PrintableOrderedType) + (Value : PrettyPrintable.PrintableOrderedType) : sig + include WithBottom - val add : Key.t -> Value.t -> t -> t [@@warning "-32"] + val add : Key.t -> Value.t -> t -> t [@@warning "-32"] - val mem : Key.t -> t -> bool [@@warning "-32"] + val mem : Key.t -> t -> bool [@@warning "-32"] - val remove : Key.t -> Value.t -> t -> t [@@warning "-32"] - end + val remove : Key.t -> Value.t -> t -> t [@@warning "-32"] + end end +module BooleanAnd : S with type t = bool (** Boolean domain ordered by p || ~q. Useful when you want a boolean that's true only when it's true in both conditional branches. *) -module BooleanAnd : S with type t = bool +module BooleanOr : WithBottom with type t = bool (** Boolean domain ordered by ~p || q. Useful when you want a boolean that's true only when it's true in one conditional branch. *) -module BooleanOr : WithBottom with type t = bool module type MaxCount = sig val max : int @@ -268,8 +260,8 @@ end module CountDomain (MaxCount : MaxCount) : sig include WithBottom with type t = private int - (** top is maximum value *) include WithTop with type t := t + (** top is maximum value *) val increment : t -> t (** bump the count by one if it is less than the max *) @@ -284,11 +276,11 @@ end (** Domain keeping a non-negative count with a bounded maximum value. [join] is minimum and [top] is zero. *) module DownwardIntDomain (MaxCount : MaxCount) : sig - (** top is zero *) include WithTop with type t = private int + (** top is zero *) - (** bottom is the provided maximum *) include WithBottom with type t := t + (** bottom is the provided maximum *) val increment : t -> t (** bump the count by one if this won't cross the maximum *) diff --git a/infer/src/absint/AbstractInterpreter.ml b/infer/src/absint/AbstractInterpreter.ml index d6f8010ce..fe069ace1 100644 --- a/infer/src/absint/AbstractInterpreter.ml +++ b/infer/src/absint/AbstractInterpreter.ml @@ -204,8 +204,7 @@ module AbstractInterpreterCommon (TransferFunctions : TransferFunctions.SIL) = s let prev = old_state.State.pre in let next = astate_pre in let res = Domain.widen ~prev ~next ~num_iters in - if Config.write_html then - debug_absint_operation (`Widen (num_iters, (prev, next, res))) ; + if Config.write_html then debug_absint_operation (`Widen (num_iters, (prev, next, res))) ; res ) else astate_pre in @@ -368,7 +367,7 @@ module MakeUsingWTO (TransferFunctions : TransferFunctions.SIL) = struct To mitigate the problem, it tries to do narrowing, in loop level, right after it found a fixpoint of a loop. Thus, it narrows before the widened values are flowed to the following loops. In order to guarantee the termination of the analysis, this eager narrowing is applied - only to the outermost loops or when the first visits of each loops. *) + only to the outermost loops or when the first visits of each loops. *) type mode = Widen | WidenThenNarrow | Narrow let is_narrowing_of = function Widen | WidenThenNarrow -> false | Narrow -> true @@ -453,8 +452,8 @@ module MakeUsingWTO (TransferFunctions : TransferFunctions.SIL) = struct let compute_post ?(do_narrowing = false) = make_compute_post ~exec_cfg_internal ~do_narrowing end -module type Make = functor (TransferFunctions : TransferFunctions.SIL) -> S - with module TransferFunctions = TransferFunctions +module type Make = functor (TransferFunctions : TransferFunctions.SIL) -> + S with module TransferFunctions = TransferFunctions module MakeRPO (T : TransferFunctions.SIL) = MakeWithScheduler (Scheduler.ReversePostorder (T.CFG)) (T) diff --git a/infer/src/absint/AbstractInterpreter.mli b/infer/src/absint/AbstractInterpreter.mli index e27ba63bd..050c12357 100644 --- a/infer/src/absint/AbstractInterpreter.mli +++ b/infer/src/absint/AbstractInterpreter.mli @@ -58,11 +58,11 @@ module type S = sig (** extract the state for a node id from the given invariant map *) end -module type Make = functor (TransferFunctions : TransferFunctions.SIL) -> S - with module TransferFunctions = TransferFunctions +module type Make = functor (TransferFunctions : TransferFunctions.SIL) -> + S with module TransferFunctions = TransferFunctions -(** create an intraprocedural abstract interpreter from transfer functions using the reverse post-order scheduler *) module MakeRPO : Make +(** create an intraprocedural abstract interpreter from transfer functions using the reverse post-order scheduler *) -(** create an intraprocedural abstract interpreter from transfer functions using Bourdoncle's strongly connected component weak topological order *) module MakeWTO : Make +(** create an intraprocedural abstract interpreter from transfer functions using Bourdoncle's strongly connected component weak topological order *) diff --git a/infer/src/absint/LowerHil.ml b/infer/src/absint/LowerHil.ml index 412deb89b..a6cb1a6b5 100644 --- a/infer/src/absint/LowerHil.ml +++ b/infer/src/absint/LowerHil.ml @@ -110,8 +110,8 @@ module MakeAbstractInterpreterWithConfig (HilConfig : HilConfig) (TransferFunctions : TransferFunctions.HIL) : S - with type domain = TransferFunctions.Domain.t - and module Interpreter = MakeAbstractInterpreter(Make(TransferFunctions)(HilConfig)) = struct + with type domain = TransferFunctions.Domain.t + and module Interpreter = MakeAbstractInterpreter(Make(TransferFunctions)(HilConfig)) = struct module LowerHilInterpreter = Make (TransferFunctions) (HilConfig) module Interpreter = MakeAbstractInterpreter (LowerHilInterpreter) diff --git a/infer/src/absint/LowerHil.mli b/infer/src/absint/LowerHil.mli index e234bc657..ef7d584b1 100644 --- a/infer/src/absint/LowerHil.mli +++ b/infer/src/absint/LowerHil.mli @@ -18,12 +18,12 @@ module DefaultConfig : HilConfig module Make (TransferFunctions : TransferFunctions.HIL) (HilConfig : HilConfig) : sig module CFG : ProcCfg.S - with type t = TransferFunctions.CFG.t - and type instrs_dir = TransferFunctions.CFG.instrs_dir - and type Node.t = TransferFunctions.CFG.Node.t - and type Node.id = TransferFunctions.CFG.Node.id - and module Node.IdMap = TransferFunctions.CFG.Node.IdMap - and module Node.IdSet = TransferFunctions.CFG.Node.IdSet + with type t = TransferFunctions.CFG.t + and type instrs_dir = TransferFunctions.CFG.instrs_dir + and type Node.t = TransferFunctions.CFG.Node.t + and type Node.id = TransferFunctions.CFG.Node.id + and module Node.IdMap = TransferFunctions.CFG.Node.IdMap + and module Node.IdSet = TransferFunctions.CFG.Node.IdSet module Domain : module type of AbstractDomain.Pair (TransferFunctions.Domain) (Bindings) @@ -68,12 +68,12 @@ module MakeAbstractInterpreterWithConfig (HilConfig : HilConfig) (TransferFunctions : TransferFunctions.HIL) : S - with type domain = TransferFunctions.Domain.t - and module Interpreter = MakeAbstractInterpreter(Make(TransferFunctions)(HilConfig)) + with type domain = TransferFunctions.Domain.t + and module Interpreter = MakeAbstractInterpreter(Make(TransferFunctions)(HilConfig)) (** Simpler version of the above wrapper that uses the default HIL config *) module MakeAbstractInterpreter (TransferFunctions : TransferFunctions.HIL) : sig include module type of - MakeAbstractInterpreterWithConfig (AbstractInterpreter.MakeRPO) (DefaultConfig) - (TransferFunctions) + MakeAbstractInterpreterWithConfig (AbstractInterpreter.MakeRPO) (DefaultConfig) + (TransferFunctions) end diff --git a/infer/src/absint/PatternMatch.ml b/infer/src/absint/PatternMatch.ml index 2577b5136..a778775cb 100644 --- a/infer/src/absint/PatternMatch.ml +++ b/infer/src/absint/PatternMatch.ml @@ -118,9 +118,7 @@ let type_get_direct_supertypes tenv (typ : Typ.t) = [] -let type_get_class_name {Typ.desc} = - match desc with Typ.Tptr (typ, _) -> Typ.name typ | _ -> None - +let type_get_class_name {Typ.desc} = match desc with Typ.Tptr (typ, _) -> Typ.name typ | _ -> None let type_get_annotation tenv (typ : Typ.t) : Annot.Item.t option = match typ.desc with diff --git a/infer/src/absint/ProcCfg.ml b/infer/src/absint/ProcCfg.ml index 66737e64e..8002c4a7f 100644 --- a/infer/src/absint/ProcCfg.ml +++ b/infer/src/absint/ProcCfg.ml @@ -216,9 +216,7 @@ module Exceptional = struct in fold_exceptional_succs pdesc n ~f:add_exn_pred ~init:exn_preds_acc in - let exceptional_preds = - Procdesc.fold_nodes pdesc ~f:add_exn_preds ~init:Procdesc.IdMap.empty - in + let exceptional_preds = Procdesc.fold_nodes pdesc ~f:add_exn_preds ~init:Procdesc.IdMap.empty in (pdesc, exceptional_preds) @@ -291,8 +289,7 @@ end (** Wrapper that reverses the direction of the CFG *) module Backward (Base : S with type instrs_dir = Instrs.not_reversed) = struct include ( - Base : - S with type t = Base.t and type instrs_dir := Base.instrs_dir and module Node = Base.Node ) + Base : S with type t = Base.t and type instrs_dir := Base.instrs_dir and module Node = Base.Node ) type instrs_dir = Instrs.reversed @@ -341,8 +338,7 @@ end = struct let instrs (node, index) = let instrs = Base.instrs node in - if Instrs.is_empty instrs then Instrs.empty - else Instrs.nth_exn instrs index |> Instrs.singleton + if Instrs.is_empty instrs then Instrs.empty else Instrs.nth_exn instrs index |> Instrs.singleton let first_of_node node = (node, 0) diff --git a/infer/src/absint/ProcCfg.mli b/infer/src/absint/ProcCfg.mli index 0db4bd16b..99bb94e3e 100644 --- a/infer/src/absint/ProcCfg.mli +++ b/infer/src/absint/ProcCfg.mli @@ -91,17 +91,14 @@ end (** Forward CFG with no exceptional control-flow *) module Normal : - S - with type t = Procdesc.t - and module Node = DefaultNode - and type instrs_dir = Instrs.not_reversed + S with type t = Procdesc.t and module Node = DefaultNode and type instrs_dir = Instrs.not_reversed (** Forward CFG with exceptional control-flow *) module Exceptional : S - with type t = Procdesc.t * DefaultNode.t list Procdesc.IdMap.t - and module Node = DefaultNode - and type instrs_dir = Instrs.not_reversed + with type t = Procdesc.t * DefaultNode.t list Procdesc.IdMap.t + and module Node = DefaultNode + and type instrs_dir = Instrs.not_reversed (** Wrapper that reverses the direction of the CFG *) module Backward (Base : S with type instrs_dir = Instrs.not_reversed) : diff --git a/infer/src/absint/SummaryPayload.ml b/infer/src/absint/SummaryPayload.ml index 9b95c2458..20b983b28 100644 --- a/infer/src/absint/SummaryPayload.ml +++ b/infer/src/absint/SummaryPayload.ml @@ -20,8 +20,7 @@ module type S = sig val of_summary : Summary.t -> t option - val read_full : - caller_summary:Summary.t -> callee_pname:Typ.Procname.t -> (Procdesc.t * t) option + val read_full : caller_summary:Summary.t -> callee_pname:Typ.Procname.t -> (Procdesc.t * t) option val read : caller_summary:Summary.t -> callee_pname:Typ.Procname.t -> t option @@ -44,8 +43,7 @@ module Make (P : Payload) : S with type t = P.t = struct let get_payload analysis_result = let open Option.Monad_infix in analysis_result - >>= fun summary -> - of_summary summary >>| fun payload -> (Summary.get_proc_desc summary, payload) + >>= fun summary -> of_summary summary >>| fun payload -> (Summary.get_proc_desc summary, payload) let read_full ~caller_summary ~callee_pname = diff --git a/infer/src/absint/SummaryPayload.mli b/infer/src/absint/SummaryPayload.mli index 10427ce78..c4f269372 100644 --- a/infer/src/absint/SummaryPayload.mli +++ b/infer/src/absint/SummaryPayload.mli @@ -22,8 +22,7 @@ module type S = sig val of_summary : Summary.t -> t option (** Read the corresponding part of the payload from the procedure summary *) - val read_full : - caller_summary:Summary.t -> callee_pname:Typ.Procname.t -> (Procdesc.t * t) option + val read_full : caller_summary:Summary.t -> callee_pname:Typ.Procname.t -> (Procdesc.t * t) option (** Return the proc desc and payload for the given procedure. Runs the analysis on-demand if necessary. *) diff --git a/infer/src/absint/TransferFunctions.mli b/infer/src/absint/TransferFunctions.mli index 8f927f8d2..da71fc140 100644 --- a/infer/src/absint/TransferFunctions.mli +++ b/infer/src/absint/TransferFunctions.mli @@ -13,8 +13,8 @@ open! IStd module type S = sig module CFG : ProcCfg.S - (** abstract domain whose state we propagate *) module Domain : AbstractDomain.S + (** abstract domain whose state we propagate *) (** read-only extra state (results of previous analyses, globals, etc.) *) type extras @@ -75,7 +75,7 @@ module MakeDisjunctive (TransferFunctions : DisjReady) (DConfig : DisjunctiveCon include SIL - with type extras = TransferFunctions.extras - and module CFG = TransferFunctions.CFG - and type Domain.t = Disjuncts.t + with type extras = TransferFunctions.extras + and module CFG = TransferFunctions.CFG + and type Domain.t = Disjuncts.t end diff --git a/infer/src/al/AL.ml b/infer/src/al/AL.ml index ba94d70b4..bdbf93b2f 100644 --- a/infer/src/al/AL.ml +++ b/infer/src/al/AL.ml @@ -21,8 +21,7 @@ let rec parse_import_file import_file channel = ; global_paths= curr_file_paths ; checkers= _ } -> already_imported_files := import_file :: !already_imported_files ; - collect_all_macros_and_paths ~from_file:import_file imports curr_file_macros - curr_file_paths + collect_all_macros_and_paths ~from_file:import_file imports curr_file_macros curr_file_paths | None -> L.(debug Linters Medium) "No macros or paths found.@\n" ; ([], []) @@ -312,7 +311,7 @@ and do_frontend_checks_decl linters (context : CLintersContext.context) let context' = CLintersContext.update_current_method context decl in ALIssues.invoke_set_of_checkers_on_node linters context' an ; (* We need to visit explicitly nodes reachable via Parameters transitions - because they won't be visited during the evaluation of the formula *) + because they won't be visited during the evaluation of the formula *) do_frontend_checks_via_transition linters context' map_active an CTL.Parameters ; ( match CAst_utils.get_method_body_opt decl with | Some stmt -> diff --git a/infer/src/al/ALIssues.ml b/infer/src/al/ALIssues.ml index 055387501..702ce8b5b 100644 --- a/infer/src/al/ALIssues.ml +++ b/infer/src/al/ALIssues.ml @@ -22,9 +22,9 @@ let filter_parsed_linters_developer parsed_linters = match Config.linter with | None -> L.(die UserError) - "In linters developer mode you should debug only one linter at a time. This is \ - important for debugging the rule. Pass the flag --linter to specify the linter \ - you want to debug." + "In linters developer mode you should debug only one linter at a time. This is important \ + for debugging the rule. Pass the flag --linter to specify the linter you want to \ + debug." | Some lint -> List.filter ~f:(fun (rule : linter) -> @@ -40,9 +40,7 @@ let filter_parsed_linters_by_path parsed_linters source_file = ~f:(fun path -> ALVar.compare_str_with_alexp (SourceFile.to_rel_path source_file) path) paths in - let whitelist_ok = - List.is_empty linter.whitelist_paths || should_lint linter.whitelist_paths - in + let whitelist_ok = List.is_empty linter.whitelist_paths || should_lint linter.whitelist_paths in let blacklist_ok = List.is_empty linter.blacklist_paths || not (should_lint linter.blacklist_paths) in @@ -343,8 +341,7 @@ let expand_formula phi map_ error_msg_ = expand f1_sub map' error_msg' | Unequal_lengths -> L.(die ExternalError) - "Formula identifier '%s' is not called with the right number of parameters" name - ) + "Formula identifier '%s' is not called with the right number of parameters" name ) with Caml.Not_found -> acc (* in this case it should be a predicate *) ) | Not f1 -> @@ -491,8 +488,8 @@ let log_frontend_issue method_decl_opt (node : Ctl_parser_types.ast_node) ~ltr:trace ~node_key -let fill_issue_desc_info_and_log context ~witness ~current_node (issue_desc : CIssue.issue_desc) - loc = +let fill_issue_desc_info_and_log context ~witness ~current_node (issue_desc : CIssue.issue_desc) loc + = let process_message message = remove_new_lines_and_whitespace (expand_message_string context message current_node) in @@ -502,8 +499,8 @@ let fill_issue_desc_info_and_log context ~witness ~current_node (issue_desc : CI try log_frontend_issue context.CLintersContext.current_method witness issue_desc' with CFrontend_errors.IncorrectAssumption e -> let trans_unit_ctx = context.CLintersContext.translation_unit_context in - ClangLogging.log_caught_exception trans_unit_ctx "IncorrectAssumption" e.position - e.source_range e.ast_node + ClangLogging.log_caught_exception trans_unit_ctx "IncorrectAssumption" e.position e.source_range + e.ast_node (* Calls the set of hard coded checkers (if any) *) @@ -540,7 +537,7 @@ let invoke_set_of_checkers_on_node parsed_linters context an = ( match an with | Ctl_parser_types.Decl (Clang_ast_t.TranslationUnitDecl _) -> (* Don't run parsed linters on TranslationUnitDecl node. - Because depending on the formula it may give an error at line -1 *) + Because depending on the formula it may give an error at line -1 *) () | _ -> if not CFrontend_config.tableaux_evaluation then diff --git a/infer/src/al/ALUtils.ml b/infer/src/al/ALUtils.ml index f104d08c7..378fa42a7 100644 --- a/infer/src/al/ALUtils.ml +++ b/infer/src/al/ALUtils.ml @@ -95,8 +95,7 @@ let receiver_method_call an = Ctl_parser_types.ast_node_name (Ctl_parser_types.Decl decl) | _ -> L.(die ExternalError) - "receiver_method_call must be called with ObjCMessageExpr, but got %s" - (tag_name_of_node an) + "receiver_method_call must be called with ObjCMessageExpr, but got %s" (tag_name_of_node an) let ivar_name an = diff --git a/infer/src/al/CTLExceptions.mli b/infer/src/al/CTLExceptions.mli index a7a71ac21..8d21a1d47 100644 --- a/infer/src/al/CTLExceptions.mli +++ b/infer/src/al/CTLExceptions.mli @@ -7,13 +7,13 @@ open! IStd -(** Raised when the parser encounters a violation of a certain invariant *) exception ALParserInvariantViolationException of string +(** Raised when the parser encounters a violation of a certain invariant *) type exc_info -(** Raised when any exception from the lexer/parser of AL is caught, to include source-location info *) exception ALFileException of exc_info +(** Raised when any exception from the lexer/parser of AL is caught, to include source-location info *) val create_exc_info : string -> Lexing.lexbuf -> exc_info diff --git a/infer/src/al/ComponentKit.ml b/infer/src/al/ComponentKit.ml index b82c7ce63..04f3ed790 100644 --- a/infer/src/al/ComponentKit.ml +++ b/infer/src/al/ComponentKit.ml @@ -60,9 +60,7 @@ let rec is_component_or_controller_descendant_impl decl = CKComponentController. Does not recurse into hierarchy. *) -and contains_ck_impl decl_list = - List.exists ~f:is_component_or_controller_descendant_impl decl_list - +and contains_ck_impl decl_list = List.exists ~f:is_component_or_controller_descendant_impl decl_list (** An easy way to fix the component kit best practice http://componentkit.org/docs/avoid-local-variables.html @@ -165,8 +163,8 @@ let mutable_local_vars_advice context an = else None with CFrontend_errors.IncorrectAssumption e -> let trans_unit_ctx = context.CLintersContext.translation_unit_context in - ClangLogging.log_caught_exception trans_unit_ctx "IncorrectAssumption" e.position - e.source_range e.ast_node ; + ClangLogging.log_caught_exception trans_unit_ctx "IncorrectAssumption" e.position e.source_range + e.ast_node ; None @@ -257,9 +255,7 @@ let component_with_unconventional_superclass_advice context an = in match an with | Ctl_parser_types.Decl (Clang_ast_t.ObjCImplementationDecl (_, _, _, _, impl_decl_info)) -> - let if_decl_opt = - CAst_utils.get_decl_opt_with_decl_ref impl_decl_info.oidi_class_interface - in + let if_decl_opt = CAst_utils.get_decl_opt_with_decl_ref impl_decl_info.oidi_class_interface in if Option.is_some if_decl_opt && is_ck_context context an then check_interface (Option.value_exn if_decl_opt) else None @@ -315,9 +311,7 @@ let component_with_multiple_factory_methods_advice context an = in match an with | Ctl_parser_types.Decl (Clang_ast_t.ObjCImplementationDecl (_, _, _, _, impl_decl_info)) -> ( - let if_decl_opt = - CAst_utils.get_decl_opt_with_decl_ref impl_decl_info.oidi_class_interface - in + let if_decl_opt = CAst_utils.get_decl_opt_with_decl_ref impl_decl_info.oidi_class_interface in match if_decl_opt with Some d when is_ck_context context an -> check_interface d | _ -> [] ) | _ -> [] diff --git a/infer/src/al/cPredicates.ml b/infer/src/al/cPredicates.ml index cb5f81d3c..0ba0a8845 100644 --- a/infer/src/al/cPredicates.ml +++ b/infer/src/al/cPredicates.ml @@ -446,11 +446,7 @@ let objc_message_receiver context an = (* an |= call_method(m) where the name must be exactly m *) let call_method an m = - match get_selector an with - | Some selector -> - ALVar.compare_str_with_alexp selector m - | _ -> - false + match get_selector an with Some selector -> ALVar.compare_str_with_alexp selector m | _ -> false let call_class_method an mname = @@ -461,8 +457,8 @@ let call_class_method an mname = ALVar.compare_str_with_alexp omei.omei_selector mname | `Instance -> (* The ObjC class type, 'Class', is treated as an instance receiver kind. - We need to check if the receiver is the class type to catch cases like - [[self class] myClassMethod] *) + We need to check if the receiver is the class type to catch cases like + [[self class] myClassMethod] *) ALVar.compare_str_with_alexp omei.omei_selector mname && is_receiver_objc_class_type an | _ -> false ) @@ -479,8 +475,8 @@ let call_instance_method an mname = ALVar.compare_str_with_alexp omei.omei_selector mname | `Instance -> (* The ObjC class type, 'Class', is treated as an instance receiver kind. - We need to verify the receiver is not the class type to avoid cases like - [[self class] myClassMethod] *) + We need to verify the receiver is not the class type to avoid cases like + [[self class] myClassMethod] *) ALVar.compare_str_with_alexp omei.omei_selector mname && not (is_receiver_objc_class_type an) | _ -> @@ -1427,9 +1423,7 @@ let rec get_decl_attributes_for_callexpr_param an = L.debug Linters Verbose "#####POINTER LOOP UP: '%i'@\n" si.si_pointer ; match CAst_utils.get_decl_opt_with_decl_ref drti.drti_decl_ref with | Some (FunctionDecl (_, _, _, fdi)) -> - List.fold fdi.fdi_parameters - ~f:(fun acc p -> List.append (get_attr_param p) acc) - ~init:[] + List.fold fdi.fdi_parameters ~f:(fun acc p -> List.append (get_attr_param p) acc) ~init:[] | Some (ParmVarDecl _ as d) -> get_attr_param d | _ -> @@ -1590,9 +1584,7 @@ let source_file_matches src_file path_re = ~default:false src_file -let is_in_source_file an path_re = - source_file_matches (Ctl_parser_types.get_source_file an) path_re - +let is_in_source_file an path_re = source_file_matches (Ctl_parser_types.get_source_file an) path_re let is_referencing_decl_from_source_file an path_re = source_file_matches (Ctl_parser_types.get_referenced_decl_source_file an) path_re diff --git a/infer/src/al/cPredicates.mli b/infer/src/al/cPredicates.mli index cfc814aea..214e117e3 100644 --- a/infer/src/al/cPredicates.mli +++ b/infer/src/al/cPredicates.mli @@ -434,8 +434,7 @@ val get_available_attr_ios_sdk : Ctl_parser_types.ast_node -> string option val get_selector : Ctl_parser_types.ast_node -> string option -val within_responds_to_selector_block : - CLintersContext.context -> Ctl_parser_types.ast_node -> bool +val within_responds_to_selector_block : CLintersContext.context -> Ctl_parser_types.ast_node -> bool val objc_method_call_within_responds_to_selector_block : CLintersContext.context -> Ctl_parser_types.ast_node -> bool diff --git a/infer/src/al/cTL.ml b/infer/src/al/cTL.ml index d54997c4c..887611a10 100644 --- a/infer/src/al/cTL.ml +++ b/infer/src/al/cTL.ml @@ -261,10 +261,10 @@ module Debug = struct match root with | Stmt (DeclStmt (_, stmts, ([VarDecl _] as var_decl))) -> (* handling special case of DeclStmt with VarDecl: emit the VarDecl node - then emit the statements in DeclStmt as children of VarDecl. This is - because despite being equal, the statements inside VarDecl and those - inside DeclStmt belong to different instances, hence they fail the - phys_equal check that should colour them *) + then emit the statements in DeclStmt as children of VarDecl. This is + because despite being equal, the statements inside VarDecl and those + inside DeclStmt belong to different instances, hence they fail the + phys_equal check that should colour them *) pp_children pp_ast_aux (fun n -> Decl n) fmt next_level var_decl ; pp_stmts fmt (next_level + 1) stmts | Stmt stmt -> diff --git a/infer/src/al/ctl_parser_types.ml b/infer/src/al/ctl_parser_types.ml index 7560ac647..100899cb8 100644 --- a/infer/src/al/ctl_parser_types.ml +++ b/infer/src/al/ctl_parser_types.ml @@ -201,9 +201,8 @@ let get_successor_stmts_of_decl decl = Option.to_list block_decl_info.Clang_ast_t.bdi_body | VarDecl (_, _, _, var_decl_info) -> Option.to_list var_decl_info.vdi_init_expr - | ObjCIvarDecl (_, _, _, fldi, _) - | FieldDecl (_, _, _, fldi) - | ObjCAtDefsFieldDecl (_, _, _, fldi) -> + | ObjCIvarDecl (_, _, _, fldi, _) | FieldDecl (_, _, _, fldi) | ObjCAtDefsFieldDecl (_, _, _, fldi) + -> Option.to_list fldi.fldi_init_expr | _ -> [] @@ -232,13 +231,13 @@ let rec is_node_successor_of ~is_successor:succ_node node = | Stmt _ -> let node_succ_stmts = get_successor_stmts node in List.exists node_succ_stmts ~f:(fun (s : Clang_ast_t.stmt) -> - ast_node_equal (Stmt s) succ_node - || is_node_successor_of ~is_successor:succ_node (Stmt s) ) + ast_node_equal (Stmt s) succ_node || is_node_successor_of ~is_successor:succ_node (Stmt s) + ) | Decl _ -> let node_succ_decls = get_successor_decls node in List.exists node_succ_decls ~f:(fun (d : Clang_ast_t.decl) -> - ast_node_equal (Decl d) succ_node - || is_node_successor_of ~is_successor:succ_node (Decl d) ) + ast_node_equal (Decl d) succ_node || is_node_successor_of ~is_successor:succ_node (Decl d) + ) let get_direct_successor_nodes an = @@ -512,8 +511,8 @@ and c_type_equal c_type abs_ctype = | BuiltinType (_, bi), BuiltIn abi -> builtin_equal bi abi | BuiltinType (_, `ObjCId), TypeName ae when ALVar.compare_str_with_alexp "instancetype" ae -> - (* This is a special case coming from an AttributedType with {ati_attr_kind=`Nonnull} where the - compiler change 'instancetype' to ObjCId *) + (* This is a special case coming from an AttributedType with {ati_attr_kind=`Nonnull} where the + compiler change 'instancetype' to ObjCId *) L.(debug Linters Verbose) "@\n Special Case when comparing BuiltInType(ObjcId) and TypeName(instancetype)\n" ; true @@ -529,8 +528,8 @@ and c_type_equal c_type abs_ctype = | ObjCObjectPointerType (_, qt), _ -> check_type_ptr qt.qt_type_ptr abs_ctype | ObjCObjectType (_, ooti), TypeName ae when ALVar.compare_str_with_alexp "instancetype" ae -> - (* This is a special case coming from an AttributedType with {ati_attr_kind=`Nonnull} where the - compiler change 'instancetype' to ObjCId *) + (* This is a special case coming from an AttributedType with {ati_attr_kind=`Nonnull} where the + compiler change 'instancetype' to ObjCId *) check_type_ptr ooti.ooti_base_type abs_ctype | ObjCObjectType _, ObjCGenProt _ -> objc_object_type_equal c_type abs_ctype diff --git a/infer/src/al/tableaux.ml b/infer/src/al/tableaux.ml index 8958b84a8..52bf6c56c 100644 --- a/infer/src/al/tableaux.ml +++ b/infer/src/al/tableaux.ml @@ -84,7 +84,7 @@ let update_linter_context_map parsed_linters an linter_context_map = else let res = Ctl_parser_types.ast_node_has_kind tl an in (*L.(debug Linters Medium) "@\n Updating linter map for node %i with '%b'" - (Ctl_parser_types.ast_node_pointer an) res; *) + (Ctl_parser_types.ast_node_pointer an) res; *) ClosureHashtbl.add phi res acc_map with Caml.Not_found -> Logging.die InternalError "Every linter condition should have an entry in the map." ) @@ -220,15 +220,15 @@ let add_valid_formulae an checker lcxt cl = let pointer = Ctl_parser_types.ast_node_pointer an in *) let add_in_set phi acc_set = (* L.(debug Linters Medium) - "@\n **** In (%i, %s) ADDING FORMULA **** @\n %a@\n@\n" pointer name CTL.Debug.pp_formula - phi ; *) + "@\n **** In (%i, %s) ADDING FORMULA **** @\n %a@\n@\n" pointer name CTL.Debug.pp_formula + phi ; *) CTLFormulaSet.add phi acc_set in let is_valid phi acc_set = CTLFormulaSet.mem phi acc_set in let do_formula acc_set phi = - (* L.(debug Linters Medium) - "@\n In (%i, %s) Dealing with formula @\n %a@\n" pointer name CTL.Debug.pp_formula phi ; - L.(debug Linters Medium) "@\n ---------------------------- @\n" ;*) + (* L.(debug Linters Medium) + "@\n In (%i, %s) Dealing with formula @\n %a@\n" pointer name CTL.Debug.pp_formula phi ; + L.(debug Linters Medium) "@\n ---------------------------- @\n" ;*) match phi with | True -> add_in_set phi acc_set @@ -294,8 +294,8 @@ let report_issue an lcxt linter (*npo_condition*) = let open Ctl_parser_types in let open ALIssues in (*let name = Ctl_parser_types.ast_node_kind an in - let pointer = Ctl_parser_types.ast_node_pointer an in - L.(debug Linters Medium) + let pointer = Ctl_parser_types.ast_node_pointer an in + L.(debug Linters Medium) "@\n@\n@\n ***** In (%i, %s) Reporting because we found @\n%a@\n@\n@\n@\n" pointer name CTL.Debug.pp_formula linter.condition ;*) let loc = ALUtils.location_from_an lcxt an in diff --git a/infer/src/backend/BackendStats.ml b/infer/src/backend/BackendStats.ml index 52395cb4b..07d406b34 100644 --- a/infer/src/backend/BackendStats.ml +++ b/infer/src/backend/BackendStats.ml @@ -105,8 +105,7 @@ let reset () = copy initial ~into:global_stats let pp f stats = let pp_hit_percent hit miss f = let total = hit + miss in - if Int.equal total 0 then F.pp_print_string f "N/A%%" - else F.fprintf f "%d%%" (hit * 100 / total) + if Int.equal total 0 then F.pp_print_string f "N/A%%" else F.fprintf f "%d%%" (hit * 100 / total) in let pp_int_field stats f field = F.fprintf f "%s= %d@;" (Field.name field) (Field.get field stats) @@ -120,8 +119,7 @@ let pp f stats = Fields.iter ~summary_file_try_load:(pp_int_field stats f) ~summary_read_from_disk:(pp_int_field stats f) ~summary_cache_hits:(pp_cache_hits stats stats.summary_cache_misses f) - ~summary_cache_misses:(pp_int_field stats f) - ~summary_has_model_queries:(pp_int_field stats f) + ~summary_cache_misses:(pp_int_field stats f) ~summary_has_model_queries:(pp_int_field stats f) ~ondemand_procs_analyzed:(pp_int_field stats f) ~ondemand_local_cache_hits:(pp_cache_hits stats stats.ondemand_local_cache_misses f) ~ondemand_local_cache_misses:(pp_int_field stats f) diff --git a/infer/src/backend/CallGraph.ml b/infer/src/backend/CallGraph.ml index 897852f7f..c0ac1276b 100644 --- a/infer/src/backend/CallGraph.ml +++ b/infer/src/backend/CallGraph.ml @@ -8,8 +8,7 @@ open! IStd module F = Format module type NodeSig = sig - type t = private - {id: int; pname: Typ.Procname.t; mutable successors: int list; mutable flag: bool} + type t = private {id: int; pname: Typ.Procname.t; mutable successors: int list; mutable flag: bool} val make : int -> Typ.Procname.t -> int list -> t @@ -144,7 +143,7 @@ let to_dotty g filename = let remove_unflagged_and_unflag_all {id_map; node_map} = NodeMap.filter_map_inplace (fun _id (n : Node.t) -> - if n.flag then ( Node.unset_flag n ; Some n ) else ( IdMap.remove id_map n.pname ; None ) ) + if n.flag then (Node.unset_flag n ; Some n) else (IdMap.remove id_map n.pname ; None) ) node_map diff --git a/infer/src/backend/CallGraph.mli b/infer/src/backend/CallGraph.mli index 1715ace50..62dfa7376 100644 --- a/infer/src/backend/CallGraph.mli +++ b/infer/src/backend/CallGraph.mli @@ -8,8 +8,7 @@ open! IStd module F = Format module type NodeSig = sig - type t = private - {id: int; pname: Typ.Procname.t; mutable successors: int list; mutable flag: bool} + type t = private {id: int; pname: Typ.Procname.t; mutable successors: int list; mutable flag: bool} val make : int -> Typ.Procname.t -> int list -> t diff --git a/infer/src/backend/Differential.ml b/infer/src/backend/Differential.ml index 9b0defda8..eb314e387 100644 --- a/infer/src/backend/Differential.ml +++ b/infer/src/backend/Differential.ml @@ -208,8 +208,8 @@ end let issue_of_cost kind CostIssues.{complexity_increase_issue; zero_issue; infinite_issue} ~delta ~prev_item - ~curr_item:( {CostItem.cost_item= cost_info; degree_with_term= curr_degree_with_term} as - curr_item ) = + ~curr_item: + ({CostItem.cost_item= cost_info; degree_with_term= curr_degree_with_term} as curr_item) = let file = cost_info.Jsonbug_t.loc.file in let method_name = cost_info.Jsonbug_t.procedure_name in let is_on_ui_thread = cost_info.Jsonbug_t.is_on_ui_thread in @@ -413,8 +413,7 @@ let of_reports ~(current_report : Jsonbug_t.report) ~(previous_report : Jsonbug_ let to_files {introduced; fixed; preexisting; costs_summary} destdir = - Out_channel.write_all (destdir ^/ "introduced.json") - ~data:(Jsonbug_j.string_of_report introduced) ; + Out_channel.write_all (destdir ^/ "introduced.json") ~data:(Jsonbug_j.string_of_report introduced) ; Out_channel.write_all (destdir ^/ "fixed.json") ~data:(Jsonbug_j.string_of_report fixed) ; Out_channel.write_all (destdir ^/ "preexisting.json") ~data:(Jsonbug_j.string_of_report preexisting) ; diff --git a/infer/src/backend/DifferentialFilters.ml b/infer/src/backend/DifferentialFilters.ml index a51486894..9a5c25edb 100644 --- a/infer/src/backend/DifferentialFilters.ml +++ b/infer/src/backend/DifferentialFilters.ml @@ -48,9 +48,8 @@ module FileRenamings = struct with Yojson.Json_error err -> L.(die UserError) "Error parsing file renamings: %s@\n\ - Expected JSON object of the following form: '%s', but instead got: '%s'" - err "{\"current\": \"aaa.java\", \"previous\": \"BBB.java\"}" - (Yojson.Basic.to_string assoc) + Expected JSON object of the following form: '%s', but instead got: '%s'" err + "{\"current\": \"aaa.java\", \"previous\": \"BBB.java\"}" (Yojson.Basic.to_string assoc) in match j with | `List json_renamings -> diff --git a/infer/src/backend/ExternalPerfData.ml b/infer/src/backend/ExternalPerfData.ml index e8205998e..c1676244d 100644 --- a/infer/src/backend/ExternalPerfData.ml +++ b/infer/src/backend/ExternalPerfData.ml @@ -72,8 +72,7 @@ let _read_file_perf_data fname = match split_class_method_name itm.Perf_profiler_t.function_name with | Some (classname, methodname) -> let procname = JProcname.make_void_signature_procname ~classname ~methodname in - global_perf_profiler_data := - PerfProfilerDataMap.add procname itm !global_perf_profiler_data + global_perf_profiler_data := PerfProfilerDataMap.add procname itm !global_perf_profiler_data | _ -> () in diff --git a/infer/src/backend/InferAnalyze.ml b/infer/src/backend/InferAnalyze.ml index 5dd0669b1..7c12d189a 100644 --- a/infer/src/backend/InferAnalyze.ml +++ b/infer/src/backend/InferAnalyze.ml @@ -7,8 +7,8 @@ *) (** Main module for the analysis after the capture phase *) -open! IStd +open! IStd module F = Format module L = Logging @@ -36,8 +36,8 @@ let analyze_target : SchedulerTypes.target Tasks.doer = let analyze_proc_name exe_env proc_name = decr procs_left ; if Int.( <= ) !procs_left 0 then ( - L.log_task "Analysing block of %d procs, starting with %a@." - per_procedure_logging_granularity Typ.Procname.pp proc_name ; + L.log_task "Analysing block of %d procs, starting with %a@." per_procedure_logging_granularity + Typ.Procname.pp proc_name ; procs_left := per_procedure_logging_granularity ) ; Ondemand.analyze_proc_name_toplevel exe_env proc_name in @@ -116,9 +116,7 @@ let get_source_files_to_analyze ~changed_files = let analyze source_files_to_analyze = if Int.equal Config.jobs 1 then ( - let target_files = - List.rev_map source_files_to_analyze ~f:(fun sf -> SchedulerTypes.File sf) - in + let target_files = List.rev_map source_files_to_analyze ~f:(fun sf -> SchedulerTypes.File sf) in Tasks.run_sequentially ~f:analyze_target target_files ; BackendStats.get () ) else ( @@ -167,8 +165,8 @@ let invalidate_changed_procedures changed_files = 0 in L.progress - "Incremental analysis: %d nodes in reverse analysis call graph, %d of which were \ - invalidated @." + "Incremental analysis: %d nodes in reverse analysis call graph, %d of which were invalidated \ + @." total_nodes invalidated_nodes ; ScubaLogging.log_count ~label:"incremental_analysis.total_nodes" ~value:total_nodes ; ScubaLogging.log_count ~label:"incremental_analysis.invalidated_nodes" ~value:invalidated_nodes ; diff --git a/infer/src/backend/InferPrint.ml b/infer/src/backend/InferPrint.ml index 43cd53258..998484989 100644 --- a/infer/src/backend/InferPrint.ml +++ b/infer/src/backend/InferPrint.ml @@ -156,16 +156,14 @@ let should_report (issue_kind : Exceptions.severity) issue_type error_desc eclas in List.mem ~equal:IssueType.equal null_deref_issue_types issue_type in - if issue_type_is_null_deref then Localise.error_desc_is_reportable_bucket error_desc - else true + if issue_type_is_null_deref then Localise.error_desc_is_reportable_bucket error_desc else true (* The reason an issue should be censored (that is, not reported). The empty string (that is "no reason") means that the issue should be reported. *) let censored_reason (issue_type : IssueType.t) source_file = let filename = SourceFile.to_rel_path source_file in - let rejected_by ((issue_type_polarity, issue_type_re), (filename_polarity, filename_re), reason) - = + let rejected_by ((issue_type_polarity, issue_type_re), (filename_polarity, filename_re), reason) = let accepted = (* matches issue_type_re implies matches filename_re *) (not (Bool.equal issue_type_polarity (Str.string_match issue_type_re issue_type.unique_id 0))) @@ -332,9 +330,8 @@ module JsonCostsPrinter = MakeJsonListPrinter (struct (CostDomain.BasicCost.pp_degree ~only_bigO:false) degree_with_term ; big_o= - Format.asprintf "%a" - (CostDomain.BasicCost.pp_degree ~only_bigO:true) - degree_with_term } + Format.asprintf "%a" (CostDomain.BasicCost.pp_degree ~only_bigO:true) degree_with_term + } in let cost_info cost = { Jsonbug_t.polynomial_version= CostDomain.BasicCost.version @@ -407,8 +404,7 @@ let pp_custom_of_report fmt report fields = | `Issue_field_hash -> Format.fprintf fmt "%s%s" (comma_separator index) (Caml.Digest.to_hex issue.hash) | `Issue_field_line_offset -> - Format.fprintf fmt "%s%d" (comma_separator index) - (issue.line - issue.procedure_start_line) + Format.fprintf fmt "%s%d" (comma_separator index) (issue.line - issue.procedure_start_line) | `Issue_field_qualifier_contains_potential_exception_note -> Format.pp_print_bool fmt (String.is_substring issue.qualifier ~substring:potential_exception_message) @@ -506,9 +502,7 @@ module Stats = struct let loc = lt.Errlog.lt_loc in let level = lt.Errlog.lt_level in let description = lt.Errlog.lt_description in - let code = - match Printer.LineReader.from_loc linereader loc with Some s -> s | None -> "" - in + let code = match Printer.LineReader.from_loc linereader loc with Some s -> s | None -> "" in let line = let pp fmt = if description <> "" then @@ -611,8 +605,7 @@ module StatsLogs = struct { analysis_nodes_visited= Summary.Stats.nb_visited summary.stats ; analysis_status= Summary.Stats.failure_kind summary.stats ; analysis_total_nodes= Summary.get_proc_desc summary |> Procdesc.get_nodes_num - ; clang_method_kind= - (match lang with Language.Clang -> Some clang_method_kind | _ -> None) + ; clang_method_kind= (match lang with Language.Clang -> Some clang_method_kind | _ -> None) ; lang= Language.to_explicit_string lang ; method_location= Summary.get_loc summary ; method_name= Typ.Procname.to_string proc_name @@ -798,11 +791,7 @@ module SummaryStats = struct module StringMap = PrettyPrintable.MakePPMap (String) type ('i, 'k) result = - | R : - { typ: 't typ - ; get: 'i -> 't - ; aggrs: ('t, 'k) MetricAggregator.t list } - -> ('i, 'k) result + | R : {typ: 't typ; get: 'i -> 't; aggrs: ('t, 'k) MetricAggregator.t list} -> ('i, 'k) result let init metrics aggregators = List.fold metrics ~init:StringMap.empty ~f:(fun acc (name, M {typ; get}) -> diff --git a/infer/src/backend/OndemandCapture.ml b/infer/src/backend/OndemandCapture.ml index 38c52a1a0..f4c989f30 100644 --- a/infer/src/backend/OndemandCapture.ml +++ b/infer/src/backend/OndemandCapture.ml @@ -19,9 +19,9 @@ let try_capture (attributes : ProcAttributes.t) : ProcAttributes.t option = let definition_file_opt = SourceFile.of_header decl_file in let try_compile definition_file = (* Use the cfg as a proxy to find out whether definition_file was already captured. If it - was, there is no point in trying to capture it again. Treat existance of the cfg as a - barrier - if it exists it means that all attributes files have been created - write logic - is defined in Cfg.store *) + was, there is no point in trying to capture it again. Treat existance of the cfg as a + barrier - if it exists it means that all attributes files have been created - write logic + is defined in Cfg.store *) if not (SourceFiles.is_captured decl_file) then ( L.(debug Capture Verbose) "Started capture of %a...@\n" SourceFile.pp definition_file ; Timeout.suspend_existing_timeout ~keep_symop_total:true ; @@ -50,9 +50,9 @@ let try_capture (attributes : ProcAttributes.t) : ProcAttributes.t option = load_defined_attributes is None, it may mean couple of things: - proc_name hasn't been captured yet, so it needs to get captured (most likely scenario) - there was a race and proc_name got captured by the time we checked whether - cfg_filename exists. In this case it's important to refetch attributes from disk because - contents may have changed (attributes file for proc_name may be there now) + cfg_filename exists. In this case it's important to refetch attributes from disk because + contents may have changed (attributes file for proc_name may be there now) Caveat: it's possible that procedure will be captured in some other unrelated file - later - infer may ignore it then. *) + later - infer may ignore it then. *) Attributes.load_defined attributes.proc_name diff --git a/infer/src/backend/Payloads.mli b/infer/src/backend/Payloads.mli index bb22e516b..7f6e54480 100644 --- a/infer/src/backend/Payloads.mli +++ b/infer/src/backend/Payloads.mli @@ -7,32 +7,31 @@ open! IStd -include - sig - (* ignore dead modules added by @@deriving fields *) - [@@@warning "-60"] +include sig + (* ignore dead modules added by @@deriving fields *) + [@@@warning "-60"] - (** analysis results *) - type t = - { annot_map: AnnotationReachabilityDomain.t option - ; biabduction: BiabductionSummary.t option - ; buffer_overrun_analysis: BufferOverrunAnalysisSummary.t option - ; buffer_overrun_checker: BufferOverrunCheckerSummary.t option - ; class_loads: ClassLoadsDomain.summary option - ; cost: CostDomain.summary option - ; impurity: ImpurityDomain.t option - ; lab_resource_leaks: ResourceLeakDomain.summary option - ; litho_graphql_field_access: LithoDomain.t option - ; litho_required_props: LithoDomain.t option - ; pulse: PulseSummary.t option - ; purity: PurityDomain.summary option - ; quandary: QuandarySummary.t option - ; racerd: RacerDDomain.summary option - ; siof: SiofDomain.Summary.t option - ; starvation: StarvationDomain.summary option - ; typestate: TypeState.t option - ; uninit: UninitDomain.Summary.t option } - [@@deriving fields] + (** analysis results *) + type t = + { annot_map: AnnotationReachabilityDomain.t option + ; biabduction: BiabductionSummary.t option + ; buffer_overrun_analysis: BufferOverrunAnalysisSummary.t option + ; buffer_overrun_checker: BufferOverrunCheckerSummary.t option + ; class_loads: ClassLoadsDomain.summary option + ; cost: CostDomain.summary option + ; impurity: ImpurityDomain.t option + ; lab_resource_leaks: ResourceLeakDomain.summary option + ; litho_graphql_field_access: LithoDomain.t option + ; litho_required_props: LithoDomain.t option + ; pulse: PulseSummary.t option + ; purity: PurityDomain.summary option + ; quandary: QuandarySummary.t option + ; racerd: RacerDDomain.summary option + ; siof: SiofDomain.Summary.t option + ; starvation: StarvationDomain.summary option + ; typestate: TypeState.t option + ; uninit: UninitDomain.Summary.t option } + [@@deriving fields] end val pp : Pp.env -> Format.formatter -> t -> unit diff --git a/infer/src/backend/PerfStats.ml b/infer/src/backend/PerfStats.ml index 909e1ec89..8b676ad0d 100644 --- a/infer/src/backend/PerfStats.ml +++ b/infer/src/backend/PerfStats.ml @@ -233,7 +233,7 @@ let compute_mem_stats () = ; minor_heap_kb= words_to_kb (float_of_int gc_ctrl.minor_heap_size) } in (* We log number of bytes instead of a larger unit in EventLogger so the EventLogger output can - display in whatever format fits best *) + display in whatever format fits best *) let mem = Some { EventLogger.minor_heap_mem= words_to_bytes gc_stats.minor_words diff --git a/infer/src/backend/SpecsFiles.ml b/infer/src/backend/SpecsFiles.ml index 3319a94ea..2647794aa 100644 --- a/infer/src/backend/SpecsFiles.ml +++ b/infer/src/backend/SpecsFiles.ml @@ -35,13 +35,13 @@ let print_usage_exit err_s = let spec_files_from_cmdline () = if CLOpt.is_originator then ( (* Find spec files specified by command-line arguments. Not run at init time since the specs - files may be generated between init and report time. *) + files may be generated between init and report time. *) List.iter ~f:(fun arg -> if (not (Filename.check_suffix arg Config.specs_files_suffix)) && arg <> "." then print_usage_exit ("file " ^ arg ^ ": arguments must be .specs files") ) Config.anon_args ; - if Config.test_filtering then ( Inferconfig.test () ; L.exit 0 ) ; + if Config.test_filtering then (Inferconfig.test () ; L.exit 0) ; if List.is_empty Config.anon_args then load_specfiles () else List.rev Config.anon_args ) else load_specfiles () diff --git a/infer/src/backend/StatsAggregator.ml b/infer/src/backend/StatsAggregator.ml index b988d5f88..3ec6908ca 100644 --- a/infer/src/backend/StatsAggregator.ml +++ b/infer/src/backend/StatsAggregator.ml @@ -86,8 +86,7 @@ let collect_all_stats_files () = let buck_out_parent = Filename.concat p Filename.parent_dir_name in let targets_files = List.map - ~f:(fun (t, p) -> - (t, find_stats_files_in_dir (concatenate_paths buck_out_parent p)) ) + ~f:(fun (t, p) -> (t, find_stats_files_in_dir (concatenate_paths buck_out_parent p))) r in Ok (Buck_out targets_files) diff --git a/infer/src/backend/callbacks.ml b/infer/src/backend/callbacks.ml index 5e994a799..d4f7c3f53 100644 --- a/infer/src/backend/callbacks.ml +++ b/infer/src/backend/callbacks.ml @@ -64,8 +64,7 @@ let iterate_procedure_callbacks exe_env summary = let is_specialized = Procdesc.is_specialized proc_desc in List.fold ~init:summary ~f:(fun summary {name; dynamic_dispatch; language; callback} -> - if Language.equal language procedure_language && (dynamic_dispatch || not is_specialized) - then ( + if Language.equal language procedure_language && (dynamic_dispatch || not is_specialized) then ( PerfEvent.( log (fun logger -> log_begin_event logger ~name ~categories:["backend"] diff --git a/infer/src/backend/dotty.ml b/infer/src/backend/dotty.ml index 9252a2a03..307128362 100644 --- a/infer/src/backend/dotty.ml +++ b/infer/src/backend/dotty.ml @@ -41,8 +41,7 @@ type coordinate = {id: int; lambda: int} [@@deriving compare] (* define a link between two nodes. src_fld/trg_fld define the label of the src/trg field. It is*) (* useful for having nodes from within a struct and/or to inside a struct *) -type link = - {kind: kind_of_links; src: coordinate; src_fld: string; trg: coordinate; trg_fld: string} +type link = {kind: kind_of_links; src: coordinate; src_fld: string; trg: coordinate; trg_fld: string} [@@deriving compare] let equal_link = [%compare.equal: link] @@ -272,8 +271,7 @@ let make_dangling_boxes pe allocated_nodes (sigma_lambda : (Sil.hpred * int) lis incr dotty_state_count ; let coo = mk_coordinate n lambda in match hpred with - | Sil.Hpointsto (_, Sil.Eexp (e, _), _) when (not (Exp.equal e Exp.zero)) && !print_full_prop - -> + | Sil.Hpointsto (_, Sil.Eexp (e, _), _) when (not (Exp.equal e Exp.zero)) && !print_full_prop -> let e_color_str = color_to_str (exp_color hpred e) in [Dotdangling (coo, e, e_color_str)] | Sil.Hlseg (_, _, _, e2, _) when not (Exp.equal e2 Exp.zero) -> @@ -324,8 +322,7 @@ let make_dangling_boxes pe allocated_nodes (sigma_lambda : (Sil.hpred * int) lis | [] -> [] | d :: candidates -> - if is_allocated d then subtract_allocated candidates - else d :: subtract_allocated candidates + if is_allocated d then subtract_allocated candidates else d :: subtract_allocated candidates in let candidate_dangling = List.concat_map ~f:get_rhs_predicate sigma_lambda in let candidate_dangling = filter_duplicate candidate_dangling [] in @@ -365,8 +362,7 @@ let rec dotty_mk_node pe sigma = let e1_color_str = color_to_str (exp_color e1) in incr dotty_state_count ; (* increment once more n+1 is the box for e4 *) - [ Dotdllseg - (mk_coordinate n lambda, e1, e2, e3, e4, k, hpara_dll.Sil.body_dll, e1_color_str) ] + [Dotdllseg (mk_coordinate n lambda, e1, e2, e3, e4, k, hpara_dll.Sil.body_dll, e1_color_str)] in match sigma with | [] -> @@ -589,8 +585,8 @@ let rec dotty_mk_set_links dotnodes sigma p f cycle = ~f:(fun (k, lab_src, m, lab_trg) -> mk_link k (mk_coordinate (n + 1) lambda) - (strip_special_chars lab_src) (mk_coordinate m lambda) - (strip_special_chars lab_trg) ) + (strip_special_chars lab_src) (mk_coordinate m lambda) (strip_special_chars lab_trg) + ) target_list in let links_from_elements = List.concat_map ~f:ff (n :: nl) in @@ -636,8 +632,8 @@ let rec dotty_mk_set_links dotnodes sigma p f cycle = trg_label ] else [] in - lnk_from_address_struct @ links_from_fields - @ dotty_mk_set_links dotnodes sigma' p f cycle ) + lnk_from_address_struct @ links_from_fields @ dotty_mk_set_links dotnodes sigma' p f cycle + ) | (Sil.Hpointsto (e, Sil.Eexp (e', _), _), lambda) :: sigma' -> ( let src = look_up dotnodes e lambda in match src with @@ -719,7 +715,7 @@ let print_kind f kind = "style=dashed; color=blue" !dotty_state_count !lambda_counter !lambda_counter "style=filled, color= lightblue" ; (* F.fprintf f "state%iL%i -> struct%iL%i:%s [color=\"lightblue \" arrowhead=none] @\n" - !dotty_state_count !lambda_counter no lev lab;*) + !dotty_state_count !lambda_counter no lev lab;*) incr dotty_state_count ) @@ -745,8 +741,8 @@ let dotty_pp_link f link = F.fprintf f "struct%iL%i:%s%iL%i -> state%iL%i[label=\"\"]@\n" n1 lambda1 src_fld n1 lambda1 n2 lambda2 | _, LinkRetainCycle -> - F.fprintf f "struct%iL%i:%s%iL%i -> struct%iL%i:%s%iL%i[label=\"\", color= red]@\n" n1 - lambda1 src_fld n1 lambda1 n2 lambda2 trg_fld n2 lambda2 + F.fprintf f "struct%iL%i:%s%iL%i -> struct%iL%i:%s%iL%i[label=\"\", color= red]@\n" n1 lambda1 + src_fld n1 lambda1 n2 lambda2 trg_fld n2 lambda2 | _, LinkStructToStruct when !print_full_prop -> F.fprintf f "struct%iL%i:%s%iL%i -> struct%iL%i:%s%iL%i[label=\"\"]@\n" n1 lambda1 src_fld n1 lambda1 n2 lambda2 trg_fld n2 lambda2 @@ -844,8 +840,7 @@ let rec print_struct f pe e te l coo c = else F.fprintf f " node [%s]; @\n struct%iL%i [label=\"{<%s%iL%i> OBJECT: %s } | %a\" ] fontcolor=%s@\n" - "shape=record" n lambda e_no_special_char n lambda print_type (struct_to_dotty_str pe coo) l - c ; + "shape=record" n lambda e_no_special_char n lambda print_type (struct_to_dotty_str pe coo) l c ; F.fprintf f "}@\n" @@ -868,9 +863,8 @@ and print_sll f pe nesting k e1 coo = incr dotty_state_count ; ( match k with | Sil.Lseg_NE -> - F.fprintf f - "subgraph cluster_%iL%i { %s node [style=filled,color=white]; label=\"list NE\";" n' - lambda "style=filled; color=lightgrey;" + F.fprintf f "subgraph cluster_%iL%i { %s node [style=filled,color=white]; label=\"list NE\";" + n' lambda "style=filled; color=lightgrey;" | Sil.Lseg_PE -> F.fprintf f "subgraph cluster_%iL%i { %s node [style=filled,color=white]; label=\"list PE\";" n' @@ -935,9 +929,7 @@ and dotty_pp_state f pe cycle dotnode = | Dotpointsto (coo, e1, c) when !print_full_prop -> dotty_exp coo e1 c false | Dotstruct (coo, e1, l, c, te) -> - let l' = - if !print_full_prop then l else List.filter ~f:(fun edge -> in_cycle cycle edge) l - in + let l' = if !print_full_prop then l else List.filter ~f:(fun edge -> in_cycle cycle edge) l in print_struct f pe e1 te l' coo c | Dotarray (coo, e1, e2, l, _, c) when !print_full_prop -> print_array f pe e1 e2 l coo c @@ -1149,8 +1141,7 @@ let pp_cfgnode pdesc fmt (n : Procdesc.Node.t) = (* don't print exception edges to the exit node *) () | _ -> - F.fprintf fmt "@\n\t %a -> %a %s;" (pp_cfgnodename pname) n1 (pp_cfgnodename pname) n2 - color + F.fprintf fmt "@\n\t %a -> %a %s;" (pp_cfgnodename pname) n1 (pp_cfgnodename pname) n2 color in List.iter ~f:(fun n' -> print_edge n n' false) (Procdesc.Node.get_succs n) ; List.iter ~f:(fun n' -> print_edge n n' true) (Procdesc.Node.get_exn n) diff --git a/infer/src/backend/errdesc.ml b/infer/src/backend/errdesc.ml index e039dd656..f34ab5df0 100644 --- a/infer/src/backend/errdesc.ml +++ b/infer/src/backend/errdesc.ml @@ -213,7 +213,7 @@ and exp_lv_dexp_ tenv (seen_ : Exp.Set.t) node e : DExp.t option = let seen = Exp.Set.add e seen_ in match Prop.exp_normalize_noabs tenv Sil.sub_empty e with | Exp.Const c -> - if verbose then ( L.d_str "exp_lv_dexp: constant " ; Sil.d_exp e ; L.d_ln () ) ; + if verbose then (L.d_str "exp_lv_dexp: constant " ; Sil.d_exp e ; L.d_ln ()) ; Some (DExp.Dderef (DExp.Dconst c)) | Exp.BinOp (Binop.PlusPI, e1, e2) -> ( if verbose then ( @@ -311,7 +311,7 @@ and exp_rv_dexp_ tenv (seen_ : Exp.Set.t) node e : DExp.t option = let seen = Exp.Set.add e seen_ in match e with | Exp.Const c -> - if verbose then ( L.d_str "exp_rv_dexp: constant " ; Sil.d_exp e ; L.d_ln () ) ; + if verbose then (L.d_str "exp_rv_dexp: constant " ; Sil.d_exp e ; L.d_ln ()) ; Some (DExp.Dconst c) | Exp.Lvar pv -> if verbose then ( @@ -346,24 +346,24 @@ and exp_rv_dexp_ tenv (seen_ : Exp.Set.t) node e : DExp.t option = | Some de1, Some de2 -> Some (DExp.Darray (de1, de2)) ) | Exp.BinOp (op, e1, e2) -> ( - if verbose then ( L.d_str "exp_rv_dexp: BinOp " ; Sil.d_exp e ; L.d_ln () ) ; + if verbose then (L.d_str "exp_rv_dexp: BinOp " ; Sil.d_exp e ; L.d_ln ()) ; match (exp_rv_dexp_ tenv seen node e1, exp_rv_dexp_ tenv seen node e2) with | None, _ | _, None -> None | Some de1, Some de2 -> Some (DExp.Dbinop (op, de1, de2)) ) | Exp.UnOp (op, e1, _) -> ( - if verbose then ( L.d_str "exp_rv_dexp: UnOp " ; Sil.d_exp e ; L.d_ln () ) ; + if verbose then (L.d_str "exp_rv_dexp: UnOp " ; Sil.d_exp e ; L.d_ln ()) ; match exp_rv_dexp_ tenv seen node e1 with | None -> None | Some de1 -> Some (DExp.Dunop (op, de1)) ) | Exp.Cast (_, e1) -> - if verbose then ( L.d_str "exp_rv_dexp: Cast " ; Sil.d_exp e ; L.d_ln () ) ; + if verbose then (L.d_str "exp_rv_dexp: Cast " ; Sil.d_exp e ; L.d_ln ()) ; exp_rv_dexp_ tenv seen node e1 | Exp.Sizeof {typ; dynamic_length; subtype} -> - if verbose then ( L.d_str "exp_rv_dexp: type " ; Sil.d_exp e ; L.d_ln () ) ; + if verbose then (L.d_str "exp_rv_dexp: type " ; Sil.d_exp e ; L.d_ln ()) ; Some (DExp.Dsizeof (typ, Option.bind dynamic_length ~f:(exp_rv_dexp_ tenv seen node), subtype)) | _ -> @@ -564,7 +564,7 @@ let explain_leak tenv hpred prop alloc_att_opt bucket = (** find the dexp, if any, where the given value is stored also return the type of the value if found *) let vpath_find tenv prop exp_ : DExp.t option * Typ.t option = - if verbose then ( L.d_str "in vpath_find exp:" ; Sil.d_exp exp_ ; L.d_ln () ) ; + if verbose then (L.d_str "in vpath_find exp:" ; Sil.d_exp exp_ ; L.d_ln ()) ; let rec find sigma_acc sigma_todo exp = let do_fse res sigma_acc' sigma_todo' lexp texp (f, se) = match se with diff --git a/infer/src/backend/errdesc.mli b/infer/src/backend/errdesc.mli index d866feaf4..ce3aa2004 100644 --- a/infer/src/backend/errdesc.mli +++ b/infer/src/backend/errdesc.mli @@ -87,8 +87,7 @@ val explain_dereference_as_caller_expression : (** return a description explaining value [exp] in [prop] in terms of a source expression using the formal parameters of the call *) -val explain_divide_by_zero : - Tenv.t -> Exp.t -> Procdesc.Node.t -> Location.t -> Localise.error_desc +val explain_divide_by_zero : Tenv.t -> Exp.t -> Procdesc.Node.t -> Location.t -> Localise.error_desc (** explain a division by zero *) val explain_condition_always_true_false : diff --git a/infer/src/backend/exe_env.ml b/infer/src/backend/exe_env.ml index 64a9cbaa4..71324456a 100644 --- a/infer/src/backend/exe_env.ml +++ b/infer/src/backend/exe_env.ml @@ -70,8 +70,8 @@ let file_data_to_tenv file_data = let file_data_to_integer_type_widths file_data = if is_none file_data.integer_type_widths then - file_data.integer_type_widths - <- Option.first_some (Typ.IntegerWidths.load file_data.source) (Some Typ.IntegerWidths.java) ; + file_data.integer_type_widths <- + Option.first_some (Typ.IntegerWidths.load file_data.source) (Some Typ.IntegerWidths.java) ; file_data.integer_type_widths diff --git a/infer/src/backend/mergeCapture.ml b/infer/src/backend/mergeCapture.ml index 7c9b147d0..098583cd8 100644 --- a/infer/src/backend/mergeCapture.ml +++ b/infer/src/backend/mergeCapture.ml @@ -19,8 +19,7 @@ let merge_global_tenvs infer_deps_file = let global_tenv_path = infer_out_src ^/ Config.global_tenv_filename |> DB.filename_from_string in - Tenv.read global_tenv_path - |> Option.iter ~f:(fun tenv -> Tenv.merge ~src:tenv ~dst:global_tenv) + Tenv.read global_tenv_path |> Option.iter ~f:(fun tenv -> Tenv.merge ~src:tenv ~dst:global_tenv) in Utils.iter_infer_deps ~project_root:Config.project_root ~f:merge infer_deps_file ; Tenv.store_global global_tenv ; diff --git a/infer/src/backend/ondemand.ml b/infer/src/backend/ondemand.ml index c9df8e69b..c32f420e4 100644 --- a/infer/src/backend/ondemand.ml +++ b/infer/src/backend/ondemand.ml @@ -191,8 +191,7 @@ let run_proc_analysis ~caller_pdesc callee_pdesc = let stats = Summary.Stats.update summary.stats ~failure_kind:kind in let payloads = let biabduction = - Some - BiabductionSummary.{preposts= []; phase= summary.payloads.biabduction |> opt_get_phase} + Some BiabductionSummary.{preposts= []; phase= summary.payloads.biabduction |> opt_get_phase} in {summary.payloads with biabduction} in @@ -231,7 +230,7 @@ let run_proc_analysis ~caller_pdesc callee_pdesc = match exn with | SymOp.Analysis_failure_exe kind -> (* in production mode, log the timeout/crash and continue with the summary we had before - the failure occurred *) + the failure occurred *) log_error_and_continue exn initial_callee_summary kind | _ -> (* this happens with assert false or some other unrecognized exception *) @@ -259,13 +258,13 @@ let dump_duplicate_procs source_file procs = { is_defined= true (* likely not needed: if [pname] is part of [procs] then it *is* defined, so we - expect the attribute to be defined too *) + expect the attribute to be defined too *) ; translation_unit ; loc } when (* defined in another file *) (not (SourceFile.equal source_file translation_unit)) && (* really defined in that file and not in an include *) - SourceFile.equal translation_unit loc.file -> + SourceFile.equal translation_unit loc.file -> Some (pname, translation_unit) | _ -> None ) @@ -275,8 +274,8 @@ let dump_duplicate_procs source_file procs = ~append:true ~perm:0o666 ~f:(fun outc -> let fmt = F.formatter_of_out_channel outc in List.iter duplicate_procs ~f:(fun (pname, source_captured) -> - F.fprintf fmt "DUPLICATE_SYMBOLS source:%a source_captured:%a pname:%a@\n" - SourceFile.pp source_file SourceFile.pp source_captured Typ.Procname.pp pname ) ; + F.fprintf fmt "DUPLICATE_SYMBOLS source:%a source_captured:%a pname:%a@\n" SourceFile.pp + source_file SourceFile.pp source_captured Typ.Procname.pp pname ) ; F.pp_print_flush fmt () ) in if not (List.is_empty duplicate_procs) then output_to_file duplicate_procs diff --git a/infer/src/backend/preanal.ml b/infer/src/backend/preanal.ml index 674d073aa..e395c4891 100644 --- a/infer/src/backend/preanal.ml +++ b/infer/src/backend/preanal.ml @@ -51,8 +51,8 @@ module VarDomain = Liveness.Domain each pvar in to_nullify afer we finish the analysis. Nullify instructions speed up the analysis by enabling it to GC state that will no longer be read. *) module NullifyTransferFunctions = struct - (** (reaching non-nullified vars) * (vars to nullify) *) module Domain = AbstractDomain.Pair (VarDomain) (VarDomain) + (** (reaching non-nullified vars) * (vars to nullify) *) module CFG = ProcCfg.Exceptional diff --git a/infer/src/backend/reporting.ml b/infer/src/backend/reporting.ml index fd69b9d33..78b5bd158 100644 --- a/infer/src/backend/reporting.ml +++ b/infer/src/backend/reporting.ml @@ -119,10 +119,10 @@ let is_suppressed ?(field_name = None) tenv proc_desc kind = let lookup = Tenv.lookup tenv in let proc_attributes = Procdesc.get_attributes proc_desc in (* Errors can be suppressed with annotations. An error of kind CHECKER_ERROR_NAME can be - suppressed with the following annotations: - - @android.annotation.SuppressLint("checker-error-name") - - @some.PrefixErrorName - where the kind matching is case - insensitive and ignores '-' and '_' characters. *) + suppressed with the following annotations: + - @android.annotation.SuppressLint("checker-error-name") + - @some.PrefixErrorName + where the kind matching is case - insensitive and ignores '-' and '_' characters. *) let annotation_matches (a : Annot.t) = let normalize str = Str.global_replace (Str.regexp "[_-]") "" (String.lowercase str) in let drop_prefix str = Str.replace_first (Str.regexp "^[A-Za-z]+_") "" str in diff --git a/infer/src/base/CommandDoc.ml b/infer/src/base/CommandDoc.ml index 2fcba4e54..bdc216e4a 100644 --- a/infer/src/base/CommandDoc.ml +++ b/infer/src/base/CommandDoc.ml @@ -43,8 +43,7 @@ let mk_command_doc ~see_also:see_also_commands ?environment:environment_opt ?fil Cmdliner.Manpage.s_files section ) ] in CLOpt.mk_command_doc ~section ~version:Version.versionString - ~date:Version.man_pages_last_modify_date ~synopsis:[`Pre synopsis] ~environment ~files - ~see_also + ~date:Version.man_pages_last_modify_date ~synopsis:[`Pre synopsis] ~environment ~files ~see_also let analyze = @@ -86,8 +85,8 @@ let compile = ~description: [ `P "Intercepts compilation commands similarly to $(b,infer-capture), but simply execute \ - these compilation commands and do not perform any translation of the source files. \ - This can be useful to configure build systems or for debugging purposes." ] + these compilation commands and do not perform any translation of the source files. This \ + can be useful to configure build systems or for debugging purposes." ] ~examples: [ `P "$(b,cmake)(1) hardcodes the absolute paths to the compiler inside the Makefiles it \ @@ -151,8 +150,8 @@ $(b,infer) $(i,[options])|} languages of the C family, and a command to build them, infer produces a list of \ potential issues." ; `P - "Infer consists of a collection of tools referenced in the $(i,SEE ALSO) section of \ - this manual. See their respective manuals for more information." + "Infer consists of a collection of tools referenced in the $(i,SEE ALSO) section of this \ + manual. See their respective manuals for more information." ; `P "When run without a subcommand, and if a compilation command is specified via the \ $(b,--) option or one of the $(b,--clang-compilation-database[-escaped]) options, then \ @@ -171,9 +170,9 @@ $(b,infer) $(i,[options])|} inferconfig_file CLOpt.args_env_var CLOpt.args_env_var inferconfig_file CLOpt.args_env_var Cmdliner.Manpage.s_environment Cmdliner.Manpage.s_files) ; `P - "Options can be specified inside an argument file $(i,file) by passing \ - $(b,@)$(i,file) as argument. The format is one option per line, and enclosing single \ - ' and double \" quotes are ignored." + "Options can be specified inside an argument file $(i,file) by passing $(b,@)$(i,file) \ + as argument. The format is one option per line, and enclosing single ' and double \" \ + quotes are ignored." ; `P "Options without a default value (e.g., $(b,--linter)) and options with list-like \ values (e.g., $(b,--Xbuck)) all have a corresponding $(b,--option-reset) flag that \ @@ -197,9 +196,9 @@ $(b,infer) $(i,[options])|} inferconfig_env_var inferconfig_file Cmdliner.Manpage.s_files) ; `P (Printf.sprintf - "If $(b,%s) is set to \"1\", then infer commands will exit with an error code in \ - some cases when otherwise a simple warning would be emitted on stderr, for instance \ - if a deprecated form of an option is used." + "If $(b,%s) is set to \"1\", then infer commands will exit with an error code in some \ + cases when otherwise a simple warning would be emitted on stderr, for instance if a \ + deprecated form of an option is used." CLOpt.strict_mode_env_var) ] ~files: [ `P @@ -224,8 +223,8 @@ $(b,infer) $(i,[options])|} ; `P "- cumulative options are JSON arrays of the appropriate type" ; `P (Printf.sprintf - "Infer will look for an $(b,%s) file in the current directory, then its parent, \ - etc., stopping at the first $(b,%s) file found." + "Infer will look for an $(b,%s) file in the current directory, then its parent, etc., \ + stopping at the first $(b,%s) file found." inferconfig_file inferconfig_file) ; `P "Example:" ; `Pre @@ -242,8 +241,8 @@ let report = ~synopsis:"$(b,infer) $(b,report) $(i,[options]) [$(i,file.specs)...]" ~description: [ `P - "Read, convert, and print .specs files in the results directory. Each spec is printed \ - to standard output unless option -q is used." + "Read, convert, and print .specs files in the results directory. Each spec is printed to \ + standard output unless option -q is used." ; `P "If no specs file are passed on the command line, process all the .specs in the results \ directory." ] @@ -254,16 +253,15 @@ let reportdiff = mk_command_doc ~title:"Infer Report Difference" ~short_description:"compute the differences between two infer reports" ~synopsis: - "$(b,infer) $(b,reportdiff) $(b,--report-current) $(i,file) $(b,--report-previous) \ - $(i,file) $(i,[options])" + "$(b,infer) $(b,reportdiff) $(b,--report-current) $(i,file) $(b,--report-previous) $(i,file) \ + $(i,[options])" ~description: [ `P "Given two infer reports $(i,previous) and $(i,current), compute the following three \ reports and store them inside the \"differential/\" subdirectory of the results \ directory:" ; `Noblank - ; `P - "- $(b,introduced.json) contains the issues found in $(i,current) but not $(i,previous);" + ; `P "- $(b,introduced.json) contains the issues found in $(i,current) but not $(i,previous);" ; `Noblank ; `P "- $(b,fixed.json) contains the issues found in $(i,previous) but not $(i,current);" ; `Noblank @@ -280,8 +278,8 @@ let events = ~synopsis:{|$(b,infer) $(b,events)|} ~description: [ `P - "Emit to stdout one JSON object per line, each describing a logged event happened \ - during the execution of Infer" ] + "Emit to stdout one JSON object per line, each describing a logged event happened during \ + the execution of Infer" ] ~see_also:InferCommand.[Report; Run] diff --git a/infer/src/base/CommandLineOption.ml b/infer/src/base/CommandLineOption.ml index 21d872828..5bf30fa45 100644 --- a/infer/src/base/CommandLineOption.ml +++ b/infer/src/base/CommandLineOption.ml @@ -99,8 +99,7 @@ type desc = ; default_string: string ; spec: spec ; decode_json: inferconfig_dir:string -> Yojson.Basic.t -> string list - (** how to go from an option in the json config file to a list of command-line options *) - } + (** how to go from an option in the json config file to a list of command-line options *) } let dashdash ?short long = match (long, short) with @@ -163,7 +162,7 @@ module SectionMap = Caml.Map.Make (struct type t = String.t (* this must be the reverse of the order in which we want the sections to appear in the - manual *) + manual *) let compare s1 s2 = if String.equal s1 s2 then (* this simplifies the next two cases *) 0 @@ -190,9 +189,7 @@ let add parse_mode sections desc = let desc_list = List.Assoc.find_exn ~equal:equal_parse_mode parse_mode_desc_lists parse_mode in desc_list := desc :: !desc_list ; let add_to_section (command, section) = - let sections = - List.Assoc.find_exn ~equal:InferCommand.equal help_sections_desc_lists command - in + let sections = List.Assoc.find_exn ~equal:InferCommand.equal help_sections_desc_lists command in let prev_contents = try SectionMap.find section !sections with Caml.Not_found -> [] in sections := SectionMap.add section (desc :: prev_contents) !sections in @@ -526,8 +523,8 @@ let map_to_str map = String.concat list ~sep:"," -let mk_string_map ?(default = String.Map.empty) ?(default_to_string = map_to_str) - ?(deprecated = []) ~long ?short ?parse_mode ?in_help ?(meta = "key=value") doc = +let mk_string_map ?(default = String.Map.empty) ?(default_to_string = map_to_str) ?(deprecated = []) + ~long ?short ?parse_mode ?in_help ?(meta = "key=value") doc = let flag = mk_flag ~deprecated ?short ~long in let split_str str = match String.lsplit2 str ~on:'=' with @@ -550,8 +547,8 @@ let mk_string_map ?(default = String.Map.empty) ?(default_to_string = map_to_str var := add_to_map !var ~key ~data ) ~mk_spec:(fun set -> String set ) (* In spirit of JSON we could have presented json as list of key-value pairs - with e.g. "key" and "value" fields, but for simplicity let's present each key-value pair - as it is passed to command line, which is a = *) + with e.g. "key" and "value" fields, but for simplicity let's present each key-value pair + as it is passed to command line, which is a = *) ~decode_json:(list_json_decoder (string_json_decoder ~flag)) @@ -568,8 +565,8 @@ let normalize_path_in_args_being_parsed ?(f = Fn.id) ~is_anon_arg str = else str -let mk_path_helper ~setter ~default_to_string ~default ~deprecated ~long ~short ~parse_mode - ~in_help ~meta ~decode_json doc = +let mk_path_helper ~setter ~default_to_string ~default ~deprecated ~long ~short ~parse_mode ~in_help + ~meta ~decode_json doc = mk ~deprecated ~long ?short ~default ?parse_mode ?in_help ~meta doc ~decode_json ~default_to_string ~mk_setter:(fun var str -> @@ -707,8 +704,8 @@ let normalize_desc_list speclist = sort speclist -let mk_command_doc ~title ~section ~version ~date ~short_description ~synopsis ~description - ?options ?exit_status ?environment ?files ?notes ?bugs ?examples ~see_also command_str = +let mk_command_doc ~title ~section ~version ~date ~short_description ~synopsis ~description ?options + ?exit_status ?environment ?files ?notes ?bugs ?examples ~see_also command_str = let add_if section blocks = match blocks with None -> `Blocks [] | Some bs -> `Blocks (`S section :: bs) in @@ -840,8 +837,7 @@ let anon_fun arg = (* stop parsing the current args and go look in that argfile *) raise (SubArguments (args_from_argfile arg)) else if - !anon_arg_action.parse_subcommands - && List.Assoc.mem !subcommand_actions ~equal:String.equal arg + !anon_arg_action.parse_subcommands && List.Assoc.mem !subcommand_actions ~equal:String.equal arg then let command_switch = List.Assoc.find_exn !subcommand_actions ~equal:String.equal arg in match (!curr_command, is_originator) with @@ -906,8 +902,8 @@ let encode_argv_to_env argv = ~f:(fun arg -> (not (String.contains arg env_var_sep)) || - ( warnf "WARNING: Ignoring unsupported option containing '%c' character: %s@\n" - env_var_sep arg ; + ( warnf "WARNING: Ignoring unsupported option containing '%c' character: %s@\n" env_var_sep + arg ; false ) ) argv) diff --git a/infer/src/base/CommandLineOption.mli b/infer/src/base/CommandLineOption.mli index 40802568e..d6a2b9685 100644 --- a/infer/src/base/CommandLineOption.mli +++ b/infer/src/base/CommandLineOption.mli @@ -124,8 +124,7 @@ val mk_symbol : (** [mk_symbol long symbols] defines a command line flag [--long ] where [(,_)] is an element of [symbols]. *) -val mk_symbol_opt : - symbols:(string * 'a) list -> ?f:('a -> 'a) -> ?mk_reset:bool -> 'a option ref t +val mk_symbol_opt : symbols:(string * 'a) list -> ?f:('a -> 'a) -> ?mk_reset:bool -> 'a option ref t (** [mk_symbol_opt] is similar to [mk_symbol] but defaults to [None]. If [mk_reset] is false then do not create an additional --[long]-reset option to reset the value of the option to [None]. *) val mk_symbol_seq : diff --git a/infer/src/base/Config.ml b/infer/src/base/Config.ml index a0277bfc6..037b91505 100644 --- a/infer/src/base/Config.ml +++ b/infer/src/base/Config.ml @@ -83,7 +83,7 @@ type os_type = Unix | Win32 | Cygwin type compilation_database_dependencies = | Deps of int option (* get the compilation database of the dependencies up to depth n - by [Deps (Some n)], or all by [Deps None] *) + by [Deps (Some n)], or all by [Deps None] *) | NoDeps [@@deriving compare] @@ -140,8 +140,7 @@ let build_system_of_exe_name name = If this is an alias for another build system that infer supports, you can use@\n\ `--force-integration ` where is one of the following supported build \ systems:@\n\ - @[ %a@]" - name + @[ %a@]" name (Pp.seq ~print_env:Pp.text_break ~sep:"" F.pp_print_string) ( List.map ~f:fst build_system_exe_assoc |> List.map ~f:string_of_build_system @@ -663,9 +662,7 @@ and { annotation_reachability ; uninit } = let mk_checker ?(default = false) ?(deprecated = []) ~long doc = let var = - CLOpt.mk_bool ~long - ~in_help:InferCommand.[(Analyze, manual_generic)] - ~default ~deprecated doc + CLOpt.mk_bool ~long ~in_help:InferCommand.[(Analyze, manual_generic)] ~default ~deprecated doc in all_checkers := (var, long, doc, default) :: !all_checkers ; var @@ -819,8 +816,8 @@ and annotation_reachability_cxx = } |} ^ "\n\ - This will cause us to create a new ISOLATED_REACHING_CONNECT issue for every function \ - whose source path starts with \"isolated/\" that may reach the function named \"connect\", \ + This will cause us to create a new ISOLATED_REACHING_CONNECT issue for every function whose \ + source path starts with \"isolated/\" that may reach the function named \"connect\", \ ignoring paths that go through a symbol matching the OCaml regexp \".*::Trusted::.*\"." ) @@ -888,8 +885,8 @@ and buck_blacklist = ~long:"buck-blacklist" ~in_help:InferCommand.[(Run, manual_buck_flavors); (Capture, manual_buck_flavors)] ~meta:"regex" - "Skip capture of files matched by the specified regular expression (only the \"flavors \ - (C++)\" Buck integration is supported, not Java)." + "Skip capture of files matched by the specified regular expression (only the \"flavors (C++)\" \ + Buck integration is supported, not Java)." and buck_build_args = @@ -935,8 +932,7 @@ and buck_out = and buck_targets_blacklist = CLOpt.mk_string_list ~long:"buck-targets-blacklist" - ~in_help: - InferCommand.[(Run, manual_buck_compilation_db); (Capture, manual_buck_compilation_db)] + ~in_help:InferCommand.[(Run, manual_buck_compilation_db); (Capture, manual_buck_compilation_db)] ~meta:"regex" "Skip capture of buck targets matched by the specified regular expression." @@ -968,8 +964,8 @@ and censor_report = filter is of the form: `::`. The first two \ components are OCaml Str regular expressions, with an optional `!` character prefix. If a \ regex has a `!` prefix, the polarity is inverted, and the filter becomes a \"blacklist\" \ - instead of a \"whitelist\". Each filter is interpreted as an implication: an issue matches \ - if it does not match the `issue_type_regex` or if it does match the `filename_regex`. The \ + instead of a \"whitelist\". Each filter is interpreted as an implication: an issue matches if \ + it does not match the `issue_type_regex` or if it does match the `filename_regex`. The \ filenames that are tested by the regex are relative to the `--project-root` directory. The \ `` is a non-empty string used to explain why the issue was filtered." @@ -1029,8 +1025,8 @@ and clang_ignore_regex = and clang_idirafter_to_override_regex = CLOpt.mk_string_opt ~long:"clang-idirafter-to-override-regex" ~meta:"dir_OCaml_regex" "Use this option in the uncommon case where the normal compilation process overrides the \ - location of internal compiler headers. This option should specify regular expression with \ - the path to those headers so that infer can use its own clang internal headers instead. \ + location of internal compiler headers. This option should specify regular expression with the \ + path to those headers so that infer can use its own clang internal headers instead. \ Concretely, this will replace $(b,-idirafter ) with $(b,-idirafter \ /path/to/infer/facebook-clang-plugins/clang/install/lib/clang//include)." @@ -1040,8 +1036,8 @@ and clang_isystem_to_override_regex = ~deprecated:["-clang-include-to-override-regex"; "-clang-include-to-override"] ~meta:"dir_OCaml_regex" "Use this option in the uncommon case where the normal compilation process overrides the \ - location of internal compiler headers. This option should specify regular expression with \ - the path to those headers so that infer can use its own clang internal headers instead. \ + location of internal compiler headers. This option should specify regular expression with the \ + path to those headers so that infer can use its own clang internal headers instead. \ Concretely, this will replace $(b,-isystem ) with $(b,-isystem \ /path/to/infer/facebook-clang-plugins/clang/install/lib/clang//include)." @@ -1069,8 +1065,8 @@ and compilation_database_escaped = CLOpt.mk_path_list ~long:"compilation-database-escaped" ~deprecated:["-clang-compilation-db-files-escaped"] ~in_help:InferCommand.[(Capture, manual_clang)] - "File that contain compilation commands where all entries are escaped for the shell, eg \ - coming from Xcode (can be specified multiple times)" + "File that contain compilation commands where all entries are escaped for the shell, eg coming \ + from Xcode (can be specified multiple times)" and compute_analytics = @@ -1195,8 +1191,7 @@ and ( biabduction_models_mode and print_buckets = CLOpt.mk_bool ~long:"print-buckets" "Show the internal bucket of Infer reports in their textual description" - and print_types = - CLOpt.mk_bool ~long:"print-types" ~default:false "Print types in symbolic heaps" + and print_types = CLOpt.mk_bool ~long:"print-types" ~default:false "Print types in symbolic heaps" and keep_going = CLOpt.mk_bool ~deprecated_no:["-no-failures-allowed"] ~long:"keep-going" ~in_help:InferCommand.[(Analyze, manual_generic)] @@ -1327,8 +1322,8 @@ and differential_filter_files = and differential_filter_set = CLOpt.mk_symbol_seq ~long:"differential-filter-set" ~eq:PolyVariantEqual.( = ) "Specify which set of the differential results is filtered with the modified files provided \ - through the $(b,--differential-modified-files) argument. By default it is applied to all \ - sets ($(b,introduced), $(b,fixed), and $(b,preexisting))" + through the $(b,--differential-modified-files) argument. By default it is applied to all sets \ + ($(b,introduced), $(b,fixed), and $(b,preexisting))" ~symbols:[("introduced", `Introduced); ("fixed", `Fixed); ("preexisting", `Preexisting)] ~default:[`Introduced; `Fixed; `Preexisting] @@ -1400,16 +1395,14 @@ and eradicate_return_over_annotated = CLOpt.mk_bool ~long:"eradicate-return-over-annotated" "Return over-annotated warning" -and eradicate_verbose = - CLOpt.mk_bool ~long:"eradicate-verbose" "Print initial and final typestates" - +and eradicate_verbose = CLOpt.mk_bool ~long:"eradicate-verbose" "Print initial and final typestates" and external_java_packages = CLOpt.mk_string_list ~long:"external-java-packages" ~in_help:InferCommand.[(Analyze, manual_java)] ~meta:"prefix" - "Specify a list of Java package prefixes for external Java packages. If set, the analysis \ - will not report non-actionable warnings on those packages." + "Specify a list of Java package prefixes for external Java packages. If set, the analysis will \ + not report non-actionable warnings on those packages." and fail_on_bug = @@ -1464,8 +1457,8 @@ and from_json_report = CLOpt.mk_path_opt ~long:"from-json-report" ~in_help:InferCommand.[(Report, manual_generic)] ~meta:"report.json" - "Load analysis results from a report file (default is to load the results from the specs \ - files generated by the analysis)." + "Load analysis results from a report file (default is to load the results from the specs files \ + generated by the analysis)." and frontend_stats = @@ -1540,8 +1533,8 @@ and hoisting_report_only_expensive = and icfg_dotty_outfile = CLOpt.mk_path_opt ~long:"icfg-dotty-outfile" ~meta:"path" - "If set, specifies path where .dot file should be written, it overrides the path for all \ - other options that would generate icfg file otherwise" + "If set, specifies path where .dot file should be written, it overrides the path for all other \ + options that would generate icfg file otherwise" and iphoneos_target_sdk_version = @@ -1623,9 +1616,9 @@ and liveness_dangerous_classes = CLOpt.mk_json ~long:"liveness-dangerous-classes" ~in_help:InferCommand.[(Analyze, manual_clang)] "Specify classes where the destructor should be ignored when computing liveness. In other \ - words, assignement to variables of these types (or common wrappers around these types such \ - as $(i,unique_ptr)) will count as dead stores when the variables are not read \ - explicitly by the program." + words, assignement to variables of these types (or common wrappers around these types such as \ + $(i,unique_ptr)) will count as dead stores when the variables are not read explicitly \ + by the program." and log_events = @@ -1695,8 +1688,7 @@ and linters_ignore_clang_failures = and linters_validate_syntax_only = CLOpt.mk_bool ~long:"linters-validate-syntax-only" ~in_help:InferCommand.[(Capture, manual_clang_linters)] - ~default:false - "Validate syntax of AL files, then emit possible errors in JSON format to stdout" + ~default:false "Validate syntax of AL files, then emit possible errors in JSON format to stdout" and load_average = @@ -1760,8 +1752,8 @@ and nullable_annotation = and nullsafe_third_party_signatures = CLOpt.mk_string_opt ~long:"nullsafe-third-party-signatures" - "Path to a folder with annotated signatures of third-party methods to be taken into account \ - by nullsafe. Path is either relative to .inferconfig folder or absolute" + "Path to a folder with annotated signatures of third-party methods to be taken into account by \ + nullsafe. Path is either relative to .inferconfig folder or absolute" and nullsafe_strict_containers = @@ -1869,8 +1861,8 @@ and procedures_attributes = and procedures_definedness = CLOpt.mk_bool ~long:"procedures-definedness" ~default:true ~in_help:InferCommand.[(Explore, manual_explore_procedures)] - "Include procedures definedness in the output of $(b,--procedures), i.e. whether the \ - procedure definition was found, or only the procedure declaration, or the procedure is an \ + "Include procedures definedness in the output of $(b,--procedures), i.e. whether the procedure \ + definition was found, or only the procedure declaration, or the procedure is an \ auto-generated Objective-C accessor" @@ -1878,8 +1870,8 @@ and procedures_filter = CLOpt.mk_string_opt ~long:"procedures-filter" ~meta:"filter" ~in_help:InferCommand.[(Explore, manual_explore_procedures)] "With $(b,--procedures), only print functions and methods (procedures) matching the specified \ - $(i,filter). A procedure filter is of the form $(i,path_pattern:procedure_name). Patterns \ - are interpreted as OCaml Str regular expressions. For instance, to keep only methods named \ + $(i,filter). A procedure filter is of the form $(i,path_pattern:procedure_name). Patterns are \ + interpreted as OCaml Str regular expressions. For instance, to keep only methods named \ \"foo\", one can use the filter \".*:foo\", or \"foo\" for short." @@ -2097,8 +2089,7 @@ and rest = ~in_help:InferCommand.[(Capture, manual_generic); (Run, manual_generic)] "Stop argument processing, use remaining arguments as a build command" ~usage:exe_usage (fun build_exe -> - match Filename.basename build_exe with "java" | "javac" -> CLOpt.Javac | _ -> CLOpt.NoParse - ) + match Filename.basename build_exe with "java" | "javac" -> CLOpt.Javac | _ -> CLOpt.NoParse ) and results_dir = @@ -2136,8 +2127,8 @@ and scuba_normals = and siof_safe_methods = CLOpt.mk_string_list ~long:"siof-safe-methods" ~in_help:InferCommand.[(Analyze, manual_siof)] - "Methods that are SIOF-safe; \"foo::bar\" will match \"foo::bar()\", \"foo::bar()\", \ - etc. (can be specified multiple times)" + "Methods that are SIOF-safe; \"foo::bar\" will match \"foo::bar()\", \"foo::bar()\", etc. \ + (can be specified multiple times)" and skip_analysis_in_path = @@ -2263,8 +2254,8 @@ and sqlite_cache_size = CLOpt.mk_int ~long:"sqlite-cache-size" ~default:2000 ~in_help: InferCommand.[(Analyze, manual_generic); (Capture, manual_generic); (Run, manual_generic)] - "SQLite cache size in pages (if positive) or kB (if negative), follows formal of \ - corresponding SQLite PRAGMA." + "SQLite cache size in pages (if positive) or kB (if negative), follows formal of corresponding \ + SQLite PRAGMA." and sqlite_page_size = @@ -2421,8 +2412,7 @@ and type_size = and uninit_interproc = - CLOpt.mk_bool ~long:"uninit-interproc" - "Run uninit check in the experimental interprocedural mode" + CLOpt.mk_bool ~long:"uninit-interproc" "Run uninit check in the experimental interprocedural mode" and unsafe_malloc = @@ -2489,7 +2479,7 @@ let javac_classes_out = ~short: 'd' (* Ensure that some form of "-d ..." is passed to javac. It's unclear whether this is strictly - needed but the tests break without this for now. See discussion in D4397716. *) + needed but the tests break without this for now. See discussion in D4397716. *) ~default:CLOpt.init_work_dir ~default_to_string:(fun _ -> ".") ~f:(fun classes_out -> diff --git a/infer/src/base/DBWriter.ml b/infer/src/base/DBWriter.ml index 1356c233f..7dea5ceea 100644 --- a/infer/src/base/DBWriter.ml +++ b/infer/src/base/DBWriter.ml @@ -12,21 +12,21 @@ module F = Format module Implementation = struct let attribute_replace_statement = (* The innermost SELECT returns either the current attributes_kind and source_file associated with - the given proc name, or default values of (-1,""). These default values have the property that - they are always "less than" any legit value. More precisely, MAX ensures that some value is - returned even if there is no row satisfying WHERE (we'll get NULL in that case, the value in - the row otherwise). COALESCE then returns the first non-NULL value, which will be either the - value of the row corresponding to that pname in the DB, or the default if no such row exists. - - The next (second-outermost) SELECT filters out that value if it is "more defined" than the ones - we would like to insert (which will never be the case if the default values are returned). If - not, it returns a trivial row (consisting solely of NULL since we don't use its values) and the - INSERT OR REPLACE will proceed and insert or update the values stored into the DB for that - pname. *) + the given proc name, or default values of (-1,""). These default values have the property that + they are always "less than" any legit value. More precisely, MAX ensures that some value is + returned even if there is no row satisfying WHERE (we'll get NULL in that case, the value in + the row otherwise). COALESCE then returns the first non-NULL value, which will be either the + value of the row corresponding to that pname in the DB, or the default if no such row exists. + + The next (second-outermost) SELECT filters out that value if it is "more defined" than the ones + we would like to insert (which will never be the case if the default values are returned). If + not, it returns a trivial row (consisting solely of NULL since we don't use its values) and the + INSERT OR REPLACE will proceed and insert or update the values stored into the DB for that + pname. *) (* TRICK: use the source file to be more deterministic in case the same procedure name is defined - in several files *) + in several files *) (* TRICK: older versions of sqlite (prior to version 3.15.0 (2016-10-14)) do not support row - values so the lexicographic ordering for (:akind, :sfile) is done by hand *) + values so the lexicographic ordering for (:akind, :sfile) is done by hand *) ResultsDatabase.register_statement {| INSERT OR REPLACE INTO procedures @@ -44,8 +44,7 @@ module Implementation = struct let replace_attributes ~pname_str ~pname ~akind ~source_file ~attributes ~proc_desc ~callees = - ResultsDatabase.with_registered_statement attribute_replace_statement - ~f:(fun db replace_stmt -> + ResultsDatabase.with_registered_statement attribute_replace_statement ~f:(fun db replace_stmt -> Sqlite3.bind replace_stmt 1 (* :pname *) pname |> SqliteUtils.check_result_code db ~log:"replace bind pname" ; Sqlite3.bind replace_stmt 2 (* :proc_name_hum *) (Sqlite3.Data.TEXT pname_str) @@ -103,9 +102,9 @@ module Implementation = struct let merge_procedures_table ~db_file = let db = ResultsDatabase.get_database () in (* Do the merge purely in SQL for great speed. The query works by doing a left join between the - sub-table and the main one, and applying the same "more defined" logic as in Attributes in the - cases where a proc_name is present in both the sub-table and the main one (main.attr_kind != - NULL). All the rows that pass this filter are inserted/updated into the main table. *) + sub-table and the main one, and applying the same "more defined" logic as in Attributes in the + cases where a proc_name is present in both the sub-table and the main one (main.attr_kind != + NULL). All the rows that pass this filter are inserted/updated into the main table. *) Sqlite3.exec db {| INSERT OR REPLACE INTO memdb.procedures @@ -146,13 +145,11 @@ module Implementation = struct let db_file = infer_out_src ^/ ResultsDatabase.database_filename in let main_db = ResultsDatabase.get_database () in Sqlite3.exec main_db (Printf.sprintf "ATTACH '%s' AS attached" db_file) - |> SqliteUtils.check_result_code main_db - ~log:(Printf.sprintf "attaching database '%s'" db_file) ; + |> SqliteUtils.check_result_code main_db ~log:(Printf.sprintf "attaching database '%s'" db_file) ; merge_procedures_table ~db_file ; merge_source_files_table ~db_file ; Sqlite3.exec main_db "DETACH attached" - |> SqliteUtils.check_result_code main_db - ~log:(Printf.sprintf "detaching database '%s'" db_file) + |> SqliteUtils.check_result_code main_db ~log:(Printf.sprintf "detaching database '%s'" db_file) let merge infer_deps_file = @@ -244,7 +241,7 @@ end type response = Ack module Server = struct - (* General comment about socket/channel destruction: closing the in_channel associated with the socket + (* General comment about socket/channel destruction: closing the in_channel associated with the socket will close the file descriptor too, so closing also the out_channel sometimes throws an exception. That's why in all code below only the input channel is ever closed. *) diff --git a/infer/src/base/Die.mli b/infer/src/base/Die.mli index d0242f3a2..daa0b4b3b 100644 --- a/infer/src/base/Die.mli +++ b/infer/src/base/Die.mli @@ -16,8 +16,8 @@ exception InferInternalError of string exception InferUserError of string -(** This can be used to avoid scattering exit invocations all over the codebase *) exception InferExit of int +(** This can be used to avoid scattering exit invocations all over the codebase *) (** kind of error for [die], with similar semantics as [Logging.{external,internal,user}_error] *) type error = ExternalError | InternalError | UserError diff --git a/infer/src/base/IssueType.ml b/infer/src/base/IssueType.ml index 843ce0d9d..9e013f614 100644 --- a/infer/src/base/IssueType.ml +++ b/infer/src/base/IssueType.ml @@ -76,7 +76,7 @@ end = struct try let old = IssueSet.find issue !all_issues in (* update human-readable string in case it was supplied this time, but keep the previous - value of enabled (see doc comment) *) + value of enabled (see doc comment) *) if Option.is_some hum0 then old.hum <- hum ; if Option.is_some doc_url then old.doc_url <- doc_url ; if Option.is_some linters_def_file then old.linters_def_file <- linters_def_file ; @@ -145,8 +145,7 @@ let checkers_allocates_memory = let checkers_annotation_reachability_error = - register_from_string "CHECKERS_ANNOTATION_REACHABILITY_ERROR" - ~hum:"Annotation Reachability Error" + register_from_string "CHECKERS_ANNOTATION_REACHABILITY_ERROR" ~hum:"Annotation Reachability Error" let checkers_calls_expensive_method = diff --git a/infer/src/base/JsonBuilder.ml b/infer/src/base/JsonBuilder.ml index 67787beac..8a27d5b72 100644 --- a/infer/src/base/JsonBuilder.ml +++ b/infer/src/base/JsonBuilder.ml @@ -17,9 +17,7 @@ let add_float ({floats} as t) ~key ~data = {t with floats= String.Map.set floats let add_string ({strings} as t) ~key ~data = {t with strings= String.Map.set strings ~key ~data} -let add_string_opt t ~key ~data = - match data with Some data -> add_string t ~key ~data | None -> t - +let add_string_opt t ~key ~data = match data with Some data -> add_string t ~key ~data | None -> t let yojson_of_integers integers = let f ~key ~data acc = (key, `Int data) :: acc in diff --git a/infer/src/base/Logging.ml b/infer/src/base/Logging.ml index c2c28ec6a..9c3fb4cfa 100644 --- a/infer/src/base/Logging.ml +++ b/infer/src/base/Logging.ml @@ -134,7 +134,7 @@ let register_formatter = let formatters = mk_formatters () in let formatters_ref = ref formatters in logging_formatters := ((formatters_ref, mk_formatters), formatters) :: !logging_formatters ; - formatters_ref) + formatters_ref ) let flush_formatters {file; console_file} = @@ -209,9 +209,7 @@ let phase fmt = log ~to_console:false phase_file_fmts fmt let progress fmt = log ~to_console:(not Config.quiet) progress_file_fmts fmt let log_task fmt = - let to_console = - match Config.progress_bar with `Plain -> true | `Quiet | `MultiLine -> false - in + let to_console = match Config.progress_bar with `Plain -> true | `Quiet | `MultiLine -> false in log ~to_console progress_file_fmts fmt @@ -277,9 +275,7 @@ let internal_error fmt = log ~to_console:true internal_error_file_fmts fmt type ocaml_pos = string * int * int * int (** Convert a ml location to a string *) -let ocaml_pos_to_string (file, lnum, cnum, enum) = - Printf.sprintf "%s:%d:%d-%d:" file lnum cnum enum - +let ocaml_pos_to_string (file, lnum, cnum, enum) = Printf.sprintf "%s:%d:%d-%d:" file lnum cnum enum (** Pretty print a location of ml source *) let pp_ocaml_pos fmt ocaml_pos = F.pp_print_string fmt (ocaml_pos_to_string ocaml_pos) diff --git a/infer/src/base/Logging.mli b/infer/src/base/Logging.mli index 8c342567c..235d3c6e4 100644 --- a/infer/src/base/Logging.mli +++ b/infer/src/base/Logging.mli @@ -61,8 +61,8 @@ val debug : debug_kind -> debug_level -> ('a, F.formatter, unit) format -> 'a val debug_dev : ('a, Format.formatter, unit) format -> 'a [@@deprecated - "Only use to debug during development. If you want more permanent logging, use \ - [Logging.debug] instead."] + "Only use to debug during development. If you want more permanent logging, use [Logging.debug] \ + instead."] [@@warning "-32"] (** For debugging during development. *) diff --git a/infer/src/base/PerfEvent.ml b/infer/src/base/PerfEvent.ml index 0594aab59..abc264592 100644 --- a/infer/src/base/PerfEvent.ml +++ b/infer/src/base/PerfEvent.ml @@ -245,7 +245,7 @@ let logger = else (* assume the trace file is here and is ready to accept list elements *) JsonFragment.(pp_state := InList :: !pp_state) ) ; - logger) + logger ) (* export logging functions that output a list element at a time and flushes so that multiple diff --git a/infer/src/base/ProcessPool.ml b/infer/src/base/ProcessPool.ml index 67dfe9ca4..905a67bef 100644 --- a/infer/src/base/ProcessPool.ml +++ b/infer/src/base/ProcessPool.ml @@ -138,8 +138,8 @@ let wait_for_updates pool buffer = let rec aux acc ~timeout = let file_descr = pool.children_updates in (* Use select(2) so that we can both wait on the pipe of children updates and wait for a - timeout. The timeout is for giving a chance to the taskbar of refreshing from time to time, - as well as for checking for new work where none were previously available. *) + timeout. The timeout is for giving a chance to the taskbar of refreshing from time to time, + as well as for checking for new work where none were previously available. *) let {Unix.Select_fds.read= read_fds} = Unix.select ~read:[file_descr] ~write:[] ~except:[] ~timeout () in @@ -150,18 +150,18 @@ let wait_for_updates pool buffer = (* no updates, break loop *) acc | [_file_descr] -> (* Read one OCaml value at a time. This is done by first reading the header of the marshalled - value (fixed size), then get the total size of the data from that header, then request a - read of the full OCaml value. - - This way the buffer is used for only one OCaml value at a time. This is simpler (values do - not overlap across the end of a read and the beginning of another) and means we do not need - a large buffer as long as messages are never bigger than the buffer. - - This works somewhat like [Marshal.from_channel] but uses the file descriptor directly - instead of an [in_channel]. Do *not* read from the pipe via an [in_channel] as they read - as much as possible eagerly. This can empty the pipe without us having a way to tell that - there is more to read anymore since the [select] call will return that there is nothing to - read. *) + value (fixed size), then get the total size of the data from that header, then request a + read of the full OCaml value. + + This way the buffer is used for only one OCaml value at a time. This is simpler (values do + not overlap across the end of a read and the beginning of another) and means we do not need + a large buffer as long as messages are never bigger than the buffer. + + This works somewhat like [Marshal.from_channel] but uses the file descriptor directly + instead of an [in_channel]. Do *not* read from the pipe via an [in_channel] as they read + as much as possible eagerly. This can empty the pipe without us having a way to tell that + there is more to read anymore since the [select] call will return that there is nothing to + read. *) really_read pool.children_updates ~buf:buffer ~len:Marshal.header_size ; let data_size = Marshal.data_size buffer 0 in really_read pool.children_updates ~buf:buffer ~pos:Marshal.header_size ~len:data_size ; @@ -251,7 +251,7 @@ let process_updates pool buffer = TaskBar.update_status pool.task_bar ~slot t status | Crash slot -> (* NOTE: the workers only send this message if {!Config.keep_going} is not [true] so if - we receive it we know we should fail hard *) + we receive it we know we should fail hard *) let {pid} = pool.slots.(slot) in (* clean crash, give the child process a chance to cleanup *) Unix.wait (`Pid pid) |> ignore ; @@ -270,8 +270,7 @@ let process_updates pool buffer = (* try to schedule more work if there are idle workers *) if not (pool.tasks.is_empty ()) then Array.iteri pool.children_states ~f:(fun slot state -> - match state with Idle -> send_work_to_child pool slot | Initializing | Processing _ -> () - ) + match state with Idle -> send_work_to_child pool slot | Initializing | Processing _ -> () ) type 'a final_worker_message = Finished of int * 'a option | FinalCrash of int @@ -420,8 +419,8 @@ let create : let file_lock = Utils.create_file_lock () in let task_bar = TaskBar.create ~jobs in (* Pipe to communicate from children to parent. Only one pipe is needed: the messages sent by - children include the identifier of the child sending the message (its [slot]). This way there - is only one pipe to wait on for updates. *) + children include the identifier of the child sending the message (its [slot]). This way there + is only one pipe to wait on for updates. *) let ((pipe_child_r, pipe_child_w) as status_pipe) = Unix.pipe () in let slots = Array.init jobs ~f:(fun slot -> diff --git a/infer/src/base/ResultsDir.ml b/infer/src/base/ResultsDir.ml index a12d3f84f..fee7de2b3 100644 --- a/infer/src/base/ResultsDir.ml +++ b/infer/src/base/ResultsDir.ml @@ -58,8 +58,7 @@ let remove_results_dir () = Result.iter_error (is_results_dir ~check_correct_version:false ()) ~f:(fun err -> L.(die UserError) "ERROR: '%s' exists but does not seem to be an infer results directory: %s@\n\ - ERROR: Please delete '%s' and try again@." - Config.results_dir err Config.results_dir ) ; + ERROR: Please delete '%s' and try again@." Config.results_dir err Config.results_dir ) ; Utils.rmtree Config.results_dir ) ; RunState.reset () @@ -81,8 +80,8 @@ let create_results_dir () = L.progress "Deleting results dir because --force-delete-results-dir was passed@." ; remove_results_dir () ) else - L.die UserError "ERROR: %s@\nPlease remove '%s' and try again" error - Config.results_dir ) ; + L.die UserError "ERROR: %s@\nPlease remove '%s' and try again" error Config.results_dir + ) ; Unix.mkdir_p Config.results_dir ; Unix.mkdir_p (Config.results_dir ^/ Config.events_dir_name) ; List.iter ~f:Unix.mkdir_p results_dir_dir_markers ; diff --git a/infer/src/base/RunState.ml b/infer/src/base/RunState.ml index 910c43c3d..b7ac25ac1 100644 --- a/infer/src/base/RunState.ml +++ b/infer/src/base/RunState.ml @@ -47,8 +47,7 @@ let load_and_validate () = "'%s' already exists but it is not an empty directory and it does not look like an \ infer results directory:\n\ \ %s\n\ - Was it created using an older version of infer?" - Config.results_dir err_msg) ) + Was it created using an older version of infer?" Config.results_dir err_msg) ) msg in if Sys.file_exists state_file_path <> `Yes then diff --git a/infer/src/base/SourceFile.ml b/infer/src/base/SourceFile.ml index ef61c0056..e89df12fd 100644 --- a/infer/src/base/SourceFile.ml +++ b/infer/src/base/SourceFile.ml @@ -100,9 +100,7 @@ let line_count source_file = count_newlines abs_path -let to_rel_path fname = - match fname with RelativeProjectRoot path -> path | _ -> to_abs_path fname - +let to_rel_path fname = match fname with RelativeProjectRoot path -> path | _ -> to_abs_path fname let invalid ml_source_file = Invalid {ml_source_file} diff --git a/infer/src/base/SourceFile.mli b/infer/src/base/SourceFile.mli index fa22bfa6a..a7b1a888c 100644 --- a/infer/src/base/SourceFile.mli +++ b/infer/src/base/SourceFile.mli @@ -9,11 +9,11 @@ open! IStd type t [@@deriving compare] -(** Maps from source_file *) module Map : Caml.Map.S with type key = t +(** Maps from source_file *) -(** Set of source files *) module Set : Caml.Set.S with type elt = t +(** Set of source files *) module Hash : Caml.Hashtbl.S with type key = t diff --git a/infer/src/base/SqliteUtils.ml b/infer/src/base/SqliteUtils.ml index 6ee16dac1..38aabbe13 100644 --- a/infer/src/base/SqliteUtils.ml +++ b/infer/src/base/SqliteUtils.ml @@ -25,8 +25,7 @@ let exec db ~log ~stmt = PerfEvent.log_begin_event logger ~name:"sql exec" ~arguments:[("stmt", `String log)] () ) ; let rc = Sqlite3.exec db stmt in PerfEvent.(log (fun logger -> log_end_event logger ())) ; - try check_result_code db ~log rc - with Error err -> error "exec: %s (%s)" err (Sqlite3.errmsg db) + try check_result_code db ~log rc with Error err -> error "exec: %s (%s)" err (Sqlite3.errmsg db) let finalize db ~log stmt = @@ -48,8 +47,7 @@ let result_fold_rows ?finalize:(do_finalize = true) db ~log stmt ~init ~f = | err -> L.die InternalError "%s: %s (%s)" log (Sqlite3.Rc.to_string err) (Sqlite3.errmsg db) in - if do_finalize then - protect ~finally:(fun () -> finalize db ~log stmt) ~f:(fun () -> aux init stmt) + if do_finalize then protect ~finally:(fun () -> finalize db ~log stmt) ~f:(fun () -> aux init stmt) else aux init stmt @@ -64,8 +62,7 @@ let zero_or_one_row ~log = function | [x] -> Some x | _ :: _ :: _ as l -> - L.die InternalError "%s: zero or one result expected, got %d rows instead" log - (List.length l) + L.die InternalError "%s: zero or one result expected, got %d rows instead" log (List.length l) let result_option ?finalize db ~log ~read_row stmt = @@ -79,8 +76,7 @@ let result_single_column_option ?finalize db ~log stmt = let result_unit ?finalize db ~log stmt = - if - not (Container.is_empty stmt ~iter:(Container.iter ~fold:(result_fold_rows ?finalize db ~log))) + if not (Container.is_empty stmt ~iter:(Container.iter ~fold:(result_fold_rows ?finalize db ~log))) then L.die InternalError "%s: the SQLite query should not return any rows" log diff --git a/infer/src/base/SqliteUtils.mli b/infer/src/base/SqliteUtils.mli index 1b4a99a65..336fa9594 100644 --- a/infer/src/base/SqliteUtils.mli +++ b/infer/src/base/SqliteUtils.mli @@ -7,9 +7,9 @@ open! IStd +exception Error of string (** The functions in this module tend to raise more often than their counterparts in [Sqlite3]. In particular, they may raise if the [Sqlite3.Rc.t] result of certain operations is unexpected. *) -exception Error of string val check_result_code : Sqlite3.db -> log:string -> Sqlite3.Rc.t -> unit (** Assert that the result is either [Sqlite3.Rc.OK] or [Sqlite3.Rc.ROW]. If the result is not diff --git a/infer/src/base/SymOp.ml b/infer/src/base/SymOp.ml index 8c257f348..89bb7416a 100644 --- a/infer/src/base/SymOp.ml +++ b/infer/src/base/SymOp.ml @@ -17,8 +17,8 @@ type failure_kind = | FKrecursion_timeout of int (** max recursion level exceeded *) | FKcrash of string (** uncaught exception or failed assertion *) -(** failure that prevented analysis from finishing *) exception Analysis_failure_exe of failure_kind +(** failure that prevented analysis from finishing *) let exn_not_failure = function Analysis_failure_exe _ -> false | _ -> true diff --git a/infer/src/base/SymOp.mli b/infer/src/base/SymOp.mli index 09dffc19b..0e841de46 100644 --- a/infer/src/base/SymOp.mli +++ b/infer/src/base/SymOp.mli @@ -59,8 +59,8 @@ type failure_kind = | FKrecursion_timeout of int (** max recursion level exceeded *) | FKcrash of string (** uncaught exception or failed assertion *) -(** Timeout exception *) exception Analysis_failure_exe of failure_kind +(** Timeout exception *) val exn_not_failure : exn -> bool (** check that the exception is not a timeout exception *) diff --git a/infer/src/base/TaskBar.ml b/infer/src/base/TaskBar.ml index c4f17e918..6dafbf309 100644 --- a/infer/src/base/TaskBar.ml +++ b/infer/src/base/TaskBar.ml @@ -70,8 +70,7 @@ let draw_top_bar fmt ~term_width ~total ~finished ~elapsed = ++ ( "%s" , max (String.length elapsed_string) 9 (* leave some room for elapsed_string to avoid flicker. 9 characters is "XXhXXmXXs" so it - gives some reasonable margin. *) - ) + gives some reasonable margin. *) ) in let top_bar_size = min term_width top_bar_size_default in let progress_bar_size = top_bar_size - size_around_progress_bar in diff --git a/infer/src/base/Utils.ml b/infer/src/base/Utils.ml index 3c16fa451..e73e771d6 100644 --- a/infer/src/base/Utils.ml +++ b/infer/src/base/Utils.ml @@ -212,9 +212,7 @@ let with_file_lock ~file_lock:{file; oc; fd} ~f = let with_intermediate_temp_file_out file ~f = - let temp_filename, temp_oc = - Filename.open_temp_file ~in_dir:(Filename.dirname file) "infer" "" - in + let temp_filename, temp_oc = Filename.open_temp_file ~in_dir:(Filename.dirname file) "infer" "" in let f () = f temp_oc in let finally () = Out_channel.close temp_oc ; diff --git a/infer/src/base/ZipLib.ml b/infer/src/base/ZipLib.ml index 0ac65d303..37ab5152b 100644 --- a/infer/src/base/ZipLib.ml +++ b/infer/src/base/ZipLib.ml @@ -41,8 +41,8 @@ let zip_libraries = None in (* Order matters: jar files should appear in the order in which they should be searched for - specs files. [Config.specs_library] is in reverse order of appearance on the command - line. *) + specs files. [Config.specs_library] is in reverse order of appearance on the command + line. *) List.rev_filter_map Config.specs_library ~f:load_zip in if @@ -50,7 +50,7 @@ let zip_libraries = && (not Config.biabduction_models_mode) && Sys.file_exists Config.biabduction_models_jar = `Yes then mk_zip_lib Config.biabduction_models_jar :: zip_libs - else zip_libs) + else zip_libs ) (** Search path in the list of zip libraries and use a cache directory to save already deserialized diff --git a/infer/src/biabduction/Abs.ml b/infer/src/biabduction/Abs.ml index 5b3a850c5..9239e1a7b 100644 --- a/infer/src/biabduction/Abs.ml +++ b/infer/src/biabduction/Abs.ml @@ -90,8 +90,8 @@ let create_condition_ls ids_private id_base p_leftover (inst : Sil.subst) = (* [fav_insts_of_private_ids] does not intersect the free vars in [p_leftover.sigma] *) Prop.sigma_free_vars p_leftover.Prop.sigma |> Fn.non intersects_fav_insts_of_private_ids && (* [fav_insts_of_private_ids] does not intersect the free vars in [insts_of_public_ids] *) - List.for_all insts_of_public_ids ~f:(fun e -> - Exp.free_vars e |> Fn.non intersects_fav_insts_of_private_ids ) + List.for_all insts_of_public_ids ~f:(fun e -> + Exp.free_vars e |> Fn.non intersects_fav_insts_of_private_ids ) let mk_rule_ptspts_ls tenv impl_ok1 impl_ok2 (para : Sil.hpara) = @@ -912,7 +912,7 @@ let abstract_gc tenv p = let check fav_seq = Sequence.is_empty fav_seq || (* non-empty intersection with [fav_p_without_pi] *) - Sequence.exists fav_seq ~f:(fun id -> Ident.Set.mem id fav_p_without_pi) + Sequence.exists fav_seq ~f:(fun id -> Ident.Set.mem id fav_p_without_pi) in let strong_filter = function | Sil.Aeq (e1, e2) | Sil.Aneq (e1, e2) -> @@ -1112,7 +1112,7 @@ let check_junk pname tenv prop = in (is_none alloc_attribute && !leaks_reported <> []) || (* None attribute only reported if it's the first one *) - List.mem ~equal:attr_opt_equal !leaks_reported alloc_attribute + List.mem ~equal:attr_opt_equal !leaks_reported alloc_attribute in let ignore_leak = !BiabductionConfig.allow_leak || ignore_resource || is_undefined diff --git a/infer/src/biabduction/Absarray.ml b/infer/src/biabduction/Absarray.ml index d33d86246..5731d0312 100644 --- a/infer/src/biabduction/Absarray.ml +++ b/infer/src/biabduction/Absarray.ml @@ -457,8 +457,8 @@ let blur_array_indices tenv (p : Prop.normal Prop.t) (root : StrexpMatch.path) (** Given [p] containing an array at [root], only keep [indices] in it *) -let keep_only_indices tenv (p : Prop.normal Prop.t) (path : StrexpMatch.path) - (indices : Exp.t list) : Prop.normal Prop.t * bool = +let keep_only_indices tenv (p : Prop.normal Prop.t) (path : StrexpMatch.path) (indices : Exp.t list) + : Prop.normal Prop.t * bool = let prune_sigma footprint_part sigma = try let matched = StrexpMatch.find_path sigma path in @@ -509,16 +509,16 @@ let strexp_do_abstract tenv footprint_part p ((path, se_in, _) : StrexpMatch.str if Config.trace_absarray && not footprint_part then L.d_strln "strexp_do_abstract (nonfootprint)" ; let prune_and_blur d_keys keep blur path keep_keys blur_keys = let p2, changed2 = - if Config.trace_absarray then ( L.d_str "keep " ; d_keys keep_keys ; L.d_ln () ) ; + if Config.trace_absarray then (L.d_str "keep " ; d_keys keep_keys ; L.d_ln ()) ; keep p path keep_keys in let p3, changed3 = if List.is_empty blur_keys then (p2, false) else ( - if Config.trace_absarray then ( L.d_str "blur " ; d_keys blur_keys ; L.d_ln () ) ; + if Config.trace_absarray then (L.d_str "blur " ; d_keys blur_keys ; L.d_ln ()) ; blur p2 path blur_keys ) in - if Config.trace_absarray then ( L.d_strln "Returns" ; Prop.d_prop p3 ; L.d_ln () ; L.d_ln () ) ; + if Config.trace_absarray then (L.d_strln "Returns" ; Prop.d_prop p3 ; L.d_ln () ; L.d_ln ()) ; (p3, changed2 || changed3) in let prune_and_blur_indices = @@ -549,7 +549,7 @@ let strexp_do_abstract tenv footprint_part p ((path, se_in, _) : StrexpMatch.str let keep_ksel = List.filter ~f:should_keep ksel in let keep_keys = List.map ~f:fst keep_ksel in let keep_keys' = if List.is_empty keep_keys then default_keys else keep_keys in - if Config.trace_absarray then ( L.d_str "keep " ; d_keys keep_keys' ; L.d_ln () ) ; + if Config.trace_absarray then (L.d_str "keep " ; d_keys keep_keys' ; L.d_ln ()) ; abstract keep_keys' [] in let do_array_reexecution esel = diff --git a/infer/src/biabduction/BiabductionSummary.mli b/infer/src/biabduction/BiabductionSummary.mli index 0742cd6b8..f14000ad6 100644 --- a/infer/src/biabduction/BiabductionSummary.mli +++ b/infer/src/biabduction/BiabductionSummary.mli @@ -41,8 +41,8 @@ module Jprop : sig (** Extract the toplevel jprop of a prop *) end -(** set of visited nodes: node id and list of lines of all the instructions *) module Visitedset : Caml.Set.S with type elt = Procdesc.Node.id * int list +(** set of visited nodes: node id and list of lines of all the instructions *) (** A spec consists of: pre: a joined prop diff --git a/infer/src/biabduction/Buckets.ml b/infer/src/biabduction/Buckets.ml index dda8ae668..527939b18 100644 --- a/infer/src/biabduction/Buckets.ml +++ b/infer/src/biabduction/Buckets.ml @@ -121,13 +121,10 @@ let check_access access_opt de_opt = Instrs.exists ~f:filter (Procdesc.Node.get_instrs node) in let do_node node = - Int.equal (Procdesc.Node.get_loc node).Location.line line_number - && has_call_or_sets_null node + Int.equal (Procdesc.Node.get_loc node).Location.line line_number && has_call_or_sets_null node in let path, pos_opt = State.get_path () in - match - IContainer.rev_filter_to_list path ~fold:Paths.Path.fold_all_nodes_nocalls ~f:do_node - with + match IContainer.rev_filter_to_list path ~fold:Paths.Path.fold_all_nodes_nocalls ~f:do_node with | [] -> None | local_access_nodes -> diff --git a/infer/src/biabduction/BuiltinDefn.ml b/infer/src/biabduction/BuiltinDefn.ml index e9e1fd306..9705b1c6f 100644 --- a/infer/src/biabduction/BuiltinDefn.ml +++ b/infer/src/biabduction/BuiltinDefn.ml @@ -20,8 +20,7 @@ let execute___builtin_va_arg {Builtin.summary; tenv; prop_; path; args; loc; exe match args with | [(lexp3, typ3)] -> let instr' = Sil.Store {e1= lexp3; root_typ= typ3; typ= typ3; e2= Exp.zero; loc} in - SymExec.instrs ~mask_errors:true exe_env tenv summary (Instrs.singleton instr') - [(prop_, path)] + SymExec.instrs ~mask_errors:true exe_env tenv summary (Instrs.singleton instr') [(prop_, path)] | _ -> raise (Exceptions.Wrong_argument_number __POS__) @@ -86,8 +85,7 @@ let add_array_to_prop tenv pdesc prop_ lexp typ = (* Add an array in prop if it is not allocated.*) -let execute___require_allocated_array {Builtin.tenv; summary; prop_; path; args} : Builtin.ret_typ - = +let execute___require_allocated_array {Builtin.tenv; summary; prop_; path; args} : Builtin.ret_typ = let pdesc = Summary.get_proc_desc summary in match args with | [(lexp, typ)] -> ( @@ -173,8 +171,7 @@ let create_type tenv n_lexp typ prop = | Typ.Tptr (typ', _) -> let sexp = Sil.Estruct ([], Sil.inst_none) in let texp = - Exp.Sizeof - {typ= typ'; nbytes= None; dynamic_length= None; subtype= Subtype.subtypes} + Exp.Sizeof {typ= typ'; nbytes= None; dynamic_length= None; subtype= Subtype.subtypes} in let hpred = Prop.mk_ptsto tenv n_lexp sexp texp in Some hpred @@ -215,8 +212,7 @@ let create_type tenv n_lexp typ prop = else null_case @ non_null_case -let execute___get_type_of {Builtin.summary; tenv; prop_; path; ret_id_typ; args} : Builtin.ret_typ - = +let execute___get_type_of {Builtin.summary; tenv; prop_; path; ret_id_typ; args} : Builtin.ret_typ = match args with | [(lexp, typ)] -> let pname = Summary.get_proc_name summary in @@ -364,8 +360,7 @@ let set_resource_attribute tenv prop path n_lexp loc ra_res = (** Set the attibute of the value as file *) -let execute___set_file_attribute {Builtin.tenv; summary; prop_; path; args; loc} : Builtin.ret_typ - = +let execute___set_file_attribute {Builtin.tenv; summary; prop_; path; args; loc} : Builtin.ret_typ = match args with | [(lexp, _)] -> let pname = Summary.get_proc_name summary in @@ -421,8 +416,7 @@ let execute___set_attr attr {Builtin.tenv; summary; prop_; path; args} : Builtin (** Delete the locked attibute of the value*) -let execute___delete_locked_attribute {Builtin.tenv; prop_; summary; path; args} : Builtin.ret_typ - = +let execute___delete_locked_attribute {Builtin.tenv; prop_; summary; path; args} : Builtin.ret_typ = match args with | [(lexp, _)] -> delete_attr tenv (Summary.get_proc_desc summary) prop_ path lexp PredSymb.Alocked @@ -497,8 +491,8 @@ let execute_free_nonzero_ mk ?(mark_as_freed = true) pdesc tenv instr prop lexp raise (Exceptions.Array_of_pointsto __POS__) ) -let execute_free mk ?(mark_as_freed = true) {Builtin.summary; instr; tenv; prop_; path; args; loc} - : Builtin.ret_typ = +let execute_free mk ?(mark_as_freed = true) {Builtin.summary; instr; tenv; prop_; path; args; loc} : + Builtin.ret_typ = match args with | [(lexp, typ)] -> let pname = Summary.get_proc_name summary in @@ -514,12 +508,12 @@ let execute_free mk ?(mark_as_freed = true) {Builtin.summary; instr; tenv; prop_ let plist = prop_zero @ (* model: if 0 then skip else execute_free_nonzero_ *) - List.concat_map - ~f:(fun p -> - execute_free_nonzero_ mk ~mark_as_freed (Summary.get_proc_desc summary) tenv instr p - (Prop.exp_normalize_prop tenv p lexp) - typ loc ) - prop_nonzero + List.concat_map + ~f:(fun p -> + execute_free_nonzero_ mk ~mark_as_freed (Summary.get_proc_desc summary) tenv instr p + (Prop.exp_normalize_prop tenv p lexp) + typ loc ) + prop_nonzero in List.map ~f:(fun p -> (p, path)) plist | _ -> @@ -607,8 +601,8 @@ let execute_alloc mk can_return_null {Builtin.summary; tenv; prop_; path; ret_id else [(prop_alloc, path)] -let execute___cxx_typeid ({Builtin.summary; tenv; prop_; args; loc; exe_env} as r) : - Builtin.ret_typ = +let execute___cxx_typeid ({Builtin.summary; tenv; prop_; args; loc; exe_env} as r) : Builtin.ret_typ + = match args with | type_info_exp :: rest -> ( let res = execute_alloc PredSymb.Mnew false {r with args= [type_info_exp]} in @@ -718,8 +712,8 @@ let execute_return_first_argument {Builtin.tenv; summary; prop_; path; ret_id_ty raise (Exceptions.Wrong_argument_number __POS__) -let execute___split_get_nth {Builtin.tenv; summary; prop_; path; ret_id_typ; args} : - Builtin.ret_typ = +let execute___split_get_nth {Builtin.tenv; summary; prop_; path; ret_id_typ; args} : Builtin.ret_typ + = match args with | [(lexp1, _); (lexp2, _); (lexp3, _)] -> ( let pname = Summary.get_proc_name summary in @@ -779,8 +773,8 @@ let execute___infer_fail {Builtin.summary; tenv; prop_; path; args; loc; exe_env (* translate builtin assertion failure *) -let execute___assert_fail {Builtin.summary; tenv; prop_; path; args; loc; exe_env} : - Builtin.ret_typ = +let execute___assert_fail {Builtin.summary; tenv; prop_; path; args; loc; exe_env} : Builtin.ret_typ + = let error_str = match List.length args with | 4 -> @@ -812,8 +806,7 @@ let execute_objc_alloc_no_fail symb_state typ alloc_fun_opt [] in let alloc_instr = - Sil.Call - (ret_id_typ, alloc_fun, [(sizeof_typ, ptr_typ)] @ alloc_fun_exp, loc, CallFlags.default) + Sil.Call (ret_id_typ, alloc_fun, [(sizeof_typ, ptr_typ)] @ alloc_fun_exp, loc, CallFlags.default) in SymExec.instrs exe_env tenv summary (Instrs.singleton alloc_instr) symb_state @@ -904,9 +897,7 @@ let __method_set_ignore_attribute = let __new = Builtin.register BuiltinDecl.__new (execute_alloc PredSymb.Mnew false) -let __new_array = - Builtin.register BuiltinDecl.__new_array (execute_alloc PredSymb.Mnew_array false) - +let __new_array = Builtin.register BuiltinDecl.__new_array (execute_alloc PredSymb.Mnew_array false) (* like __objc_alloc, but does not return nil *) let __objc_alloc_no_fail = diff --git a/infer/src/biabduction/BuiltinDefn.mli b/infer/src/biabduction/BuiltinDefn.mli index aac4ad1b9..737cf4e0d 100644 --- a/infer/src/biabduction/BuiltinDefn.mli +++ b/infer/src/biabduction/BuiltinDefn.mli @@ -7,8 +7,8 @@ open! IStd -(** Models for the builtin functions supported *) include BUILTINS.S with type t = Builtin.registered +(** Models for the builtin functions supported *) val init : unit -> unit (** Clients of Builtin module should call this before Builtin module is used. diff --git a/infer/src/biabduction/Dom.ml b/infer/src/biabduction/Dom.ml index eb98efaa7..526fb2809 100644 --- a/infer/src/biabduction/Dom.ml +++ b/infer/src/biabduction/Dom.ml @@ -32,7 +32,7 @@ let equal_sigma sigma1 sigma2 = L.d_strln "failure reason 1" ; raise Sil.JoinFail | hpred1 :: sigma1_rest', hpred2 :: sigma2_rest' -> if Sil.equal_hpred hpred1 hpred2 then f sigma1_rest' sigma2_rest' - else ( L.d_strln "failure reason 2" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 2" ; raise Sil.JoinFail) in let sigma1_sorted = List.sort ~compare:Sil.compare_hpred sigma1 in let sigma2_sorted = List.sort ~compare:Sil.compare_hpred sigma2 in @@ -119,7 +119,7 @@ end = struct let new_c = lookup_const' const_tbl new_r in let old_c = lookup_const' const_tbl old_r in let res_c = Exp.Set.union new_c old_c in - if Exp.Set.cardinal res_c > 1 then ( L.d_strln "failure reason 3" ; raise Sil.JoinFail ) ; + if Exp.Set.cardinal res_c > 1 then (L.d_strln "failure reason 3" ; raise Sil.JoinFail) ; Hashtbl.replace tbl old_r new_r ; Hashtbl.replace const_tbl new_r res_c @@ -127,7 +127,7 @@ end = struct let replace_const' tbl const_tbl e c = let r = find' tbl e in let set = Exp.Set.add c (lookup_const' const_tbl r) in - if Exp.Set.cardinal set > 1 then ( L.d_strln "failure reason 4" ; raise Sil.JoinFail ) ; + if Exp.Set.cardinal set > 1 then (L.d_strln "failure reason 4" ; raise Sil.JoinFail) ; Hashtbl.replace const_tbl r set @@ -148,12 +148,12 @@ end = struct L.d_strln "failure reason 5" ; raise Sil.JoinFail ) | Exp.Var id, Exp.Const _ | Exp.Var id, Exp.Lvar _ -> if can_rename id then replace_const' tbl const_tbl e e' - else ( L.d_strln "failure reason 6" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 6" ; raise Sil.JoinFail) | Exp.Const _, Exp.Var id' | Exp.Lvar _, Exp.Var id' -> if can_rename id' then replace_const' tbl const_tbl e' e - else ( L.d_strln "failure reason 7" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 7" ; raise Sil.JoinFail) | _ -> - if not (Exp.equal e e') then ( L.d_strln "failure reason 8" ; raise Sil.JoinFail ) else () + if not (Exp.equal e e') then (L.d_strln "failure reason 8" ; raise Sil.JoinFail) else () let check side es = @@ -588,15 +588,15 @@ end = struct let res = ref [] in let f v = match (v, side) with - | (Exp.BinOp (Binop.PlusA _, e1', Exp.Const (Const.Cint i)), e2, e'), Lhs - when Exp.equal e e1' -> + | (Exp.BinOp (Binop.PlusA _, e1', Exp.Const (Const.Cint i)), e2, e'), Lhs when Exp.equal e e1' + -> let c' = Exp.int (IntLit.neg i) in let v' = (e1', Exp.BinOp (Binop.PlusA None, e2, c'), Exp.BinOp (Binop.PlusA None, e', c')) in res := v' :: !res - | (e1, Exp.BinOp (Binop.PlusA _, e2', Exp.Const (Const.Cint i)), e'), Rhs - when Exp.equal e e2' -> + | (e1, Exp.BinOp (Binop.PlusA _, e2', Exp.Const (Const.Cint i)), e'), Rhs when Exp.equal e e2' + -> let c' = Exp.int (IntLit.neg i) in let v' = (Exp.BinOp (Binop.PlusA None, e1, c'), e2', Exp.BinOp (Binop.PlusA None, e', c')) @@ -668,8 +668,8 @@ end = struct end) (* Each triple (L,R,U) in !tbl gives rise to an edge (Lhs,L)--(Rhs,R) - labeled by U. For each connected component, return equalities that constrain - all its Us to be equal. *) + labeled by U. For each connected component, return equalities that constrain + all its Us to be equal. *) let get_unify_eqs () : (Exp.t * Exp.t) list = let find_classes () = let module UF = Union_find in @@ -750,7 +750,7 @@ end = struct let get_other_atoms tenv side atom_in = let build_other_atoms construct side e = - if Config.trace_join then ( L.d_str "build_other_atoms: " ; Sil.d_exp e ; L.d_ln () ) ; + if Config.trace_join then (L.d_str "build_other_atoms: " ; Sil.d_exp e ; L.d_ln ()) ; let others1 = get_others_direct_or_induced side e in let others2 = match others1 with None -> get_others_deep side e | Some _ -> others1 in match others2 with @@ -778,7 +778,7 @@ end = struct | Sil.Aneq ((Exp.Var id as e), e') when exp_contains_only_normal_ids e' && not (Ident.is_normal id) -> (* e' cannot also be a normal id according to the guard so we can consider the two cases - separately (this case and the next) *) + separately (this case and the next) *) build_other_atoms (fun e0 -> Prop.mk_neq tenv e0 e') side e | Sil.Aneq (e', (Exp.Var id as e)) when exp_contains_only_normal_ids e' && not (Ident.is_normal id) -> @@ -792,7 +792,7 @@ end = struct | Sil.Aeq ((Exp.Var id as e), e') when exp_contains_only_normal_ids e' && not (Ident.is_normal id) -> (* e' cannot also be a normal id according to the guard so we can consider the two cases - separately (this case and the next) *) + separately (this case and the next) *) build_other_atoms (fun e0 -> Prop.mk_eq tenv e0 e') side e | Sil.Aeq (e', (Exp.Var id as e)) when exp_contains_only_normal_ids e' && not (Ident.is_normal id) -> @@ -831,8 +831,7 @@ end = struct if (not (Exp.free_vars e1 |> Sequence.exists ~f:can_rename)) && not (Exp.free_vars e2 |> Sequence.exists ~f:can_rename) - then - if Exp.equal e1 e2 then e1 else ( L.d_strln "failure reason 13" ; raise Sil.JoinFail ) + then if Exp.equal e1 e2 then e1 else (L.d_strln "failure reason 13" ; raise Sil.JoinFail) else match default_op with | ExtDefault e -> @@ -920,7 +919,7 @@ let ident_partial_join (id1 : Ident.t) (id2 : Ident.t) = match (Ident.is_normal id1, Ident.is_normal id2) with | true, true -> if Ident.equal id1 id2 then Exp.Var id1 - else ( L.d_strln "failure reason 14" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 14" ; raise Sil.JoinFail) | true, _ | _, true -> Rename.extend (Exp.Var id1) (Exp.Var id2) Rename.ExtFresh | _ -> @@ -936,7 +935,7 @@ let ident_partial_meet (id1 : Ident.t) (id2 : Ident.t) = match (Ident.is_normal id1, Ident.is_normal id2) with | true, true -> if Ident.equal id1 id2 then Exp.Var id1 - else ( L.d_strln "failure reason 16" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 16" ; raise Sil.JoinFail) | true, _ -> let e1, e2 = (Exp.Var id1, Exp.Var id2) in Rename.extend e1 e2 (Rename.ExtDefault e1) @@ -949,7 +948,7 @@ let ident_partial_meet (id1 : Ident.t) (id2 : Ident.t) = else if Ident.is_footprint id1 && Ident.equal id1 id2 then let e = Exp.Var id1 in Rename.extend e e (Rename.ExtDefault e) - else ( L.d_strln "failure reason 17" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 17" ; raise Sil.JoinFail) (** {2 Join and Meet for Exps} *) @@ -965,7 +964,7 @@ let const_partial_join c1 c2 = L.d_strln "failure reason 18" ; raise Sil.JoinFail ) else if !BiabductionConfig.abs_val >= 2 then FreshVarExp.get_fresh_exp (Exp.Const c1) (Exp.Const c2) - else ( L.d_strln "failure reason 19" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 19" ; raise Sil.JoinFail) let rec exp_partial_join (e1 : Exp.t) (e2 : Exp.t) : Exp.t = @@ -974,12 +973,12 @@ let rec exp_partial_join (e1 : Exp.t) (e2 : Exp.t) : Exp.t = | Exp.Var id1, Exp.Var id2 -> ident_partial_join id1 id2 | Exp.Var id, Exp.Const _ | Exp.Const _, Exp.Var id -> - if Ident.is_normal id then ( L.d_strln "failure reason 20" ; raise Sil.JoinFail ) + if Ident.is_normal id then (L.d_strln "failure reason 20" ; raise Sil.JoinFail) else Rename.extend e1 e2 Rename.ExtFresh | Exp.Const c1, Exp.Const c2 -> const_partial_join c1 c2 | Exp.Var id, Exp.Lvar _ | Exp.Lvar _, Exp.Var id -> - if Ident.is_normal id then ( L.d_strln "failure reason 21" ; raise Sil.JoinFail ) + if Ident.is_normal id then (L.d_strln "failure reason 21" ; raise Sil.JoinFail) else Rename.extend e1 e2 Rename.ExtFresh | Exp.BinOp (Binop.PlusA _, Exp.Var id1, Exp.Const _), Exp.Var id2 | Exp.Var id1, Exp.BinOp (Binop.PlusA _, Exp.Var id2, Exp.Const _) @@ -996,12 +995,12 @@ let rec exp_partial_join (e1 : Exp.t) (e2 : Exp.t) : Exp.t = let e_res = Rename.extend (Exp.int c1') (Exp.Var id2) Rename.ExtFresh in Exp.BinOp (Binop.PlusA None, e_res, Exp.int c2) | Exp.Cast (t1, e1), Exp.Cast (t2, e2) -> - if not (Typ.equal t1 t2) then ( L.d_strln "failure reason 22" ; raise Sil.JoinFail ) + if not (Typ.equal t1 t2) then (L.d_strln "failure reason 22" ; raise Sil.JoinFail) else let e1'' = exp_partial_join e1 e2 in Exp.Cast (t1, e1'') | Exp.UnOp (unop1, e1, topt1), Exp.UnOp (unop2, e2, _) -> - if not (Unop.equal unop1 unop2) then ( L.d_strln "failure reason 23" ; raise Sil.JoinFail ) + if not (Unop.equal unop1 unop2) then (L.d_strln "failure reason 23" ; raise Sil.JoinFail) else Exp.UnOp (unop1, exp_partial_join e1 e2, topt1) (* should be topt1 = topt2 *) | Exp.BinOp (Binop.PlusPI, e1, e1'), Exp.BinOp (Binop.PlusPI, e2, e2') -> let e1'' = exp_partial_join e1 e2 in @@ -1014,16 +1013,16 @@ let rec exp_partial_join (e1 : Exp.t) (e2 : Exp.t) : Exp.t = in Exp.BinOp (Binop.PlusPI, e1'', e2'') | Exp.BinOp (binop1, e1, e1'), Exp.BinOp (binop2, e2, e2') -> - if not (Binop.equal binop1 binop2) then ( L.d_strln "failure reason 24" ; raise Sil.JoinFail ) + if not (Binop.equal binop1 binop2) then (L.d_strln "failure reason 24" ; raise Sil.JoinFail) else let e1'' = exp_partial_join e1 e2 in let e2'' = exp_partial_join e1' e2' in Exp.BinOp (binop1, e1'', e2'') | Exp.Lvar pvar1, Exp.Lvar pvar2 -> - if not (Pvar.equal pvar1 pvar2) then ( L.d_strln "failure reason 25" ; raise Sil.JoinFail ) + if not (Pvar.equal pvar1 pvar2) then (L.d_strln "failure reason 25" ; raise Sil.JoinFail) else e1 | Exp.Lfield (e1, f1, t1), Exp.Lfield (e2, f2, _) -> - if not (Typ.Fieldname.equal f1 f2) then ( L.d_strln "failure reason 26" ; raise Sil.JoinFail ) + if not (Typ.Fieldname.equal f1 f2) then (L.d_strln "failure reason 26" ; raise Sil.JoinFail) else Exp.Lfield (exp_partial_join e1 e2, f1, t1) (* should be t1 = t2 *) | Exp.Lindex (e1, e1'), Exp.Lindex (e2, e2') -> let e1'' = exp_partial_join e1 e2 in @@ -1073,8 +1072,7 @@ and typ_partial_join (t1 : Typ.t) (t2 : Typ.t) = match (t1.desc, t2.desc) with | Typ.Tptr (t1, pk1), Typ.Tptr (t2, pk2) when Typ.equal_ptr_kind pk1 pk2 && Typ.equal_quals t1.quals t2.quals -> - Typ.mk ~default:t1 (Tptr (typ_partial_join t1 t2, pk1)) - (* quals are the same for t1 and t2 *) + Typ.mk ~default:t1 (Tptr (typ_partial_join t1 t2, pk1)) (* quals are the same for t1 and t2 *) | ( Typ.Tarray {elt= typ1; length= len1; stride= stride1} , Typ.Tarray {elt= typ2; length= len2; stride= stride2} ) when Typ.equal_quals typ1.quals typ2.quals -> @@ -1100,37 +1098,37 @@ let rec exp_partial_meet (e1 : Exp.t) (e2 : Exp.t) : Exp.t = ident_partial_meet id1 id2 | Exp.Var id, Exp.Const _ -> if not (Ident.is_normal id) then Rename.extend e1 e2 (Rename.ExtDefault e2) - else ( L.d_strln "failure reason 27" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 27" ; raise Sil.JoinFail) | Exp.Const _, Exp.Var id -> if not (Ident.is_normal id) then Rename.extend e1 e2 (Rename.ExtDefault e1) - else ( L.d_strln "failure reason 28" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 28" ; raise Sil.JoinFail) | Exp.Const c1, Exp.Const c2 -> - if Const.equal c1 c2 then e1 else ( L.d_strln "failure reason 29" ; raise Sil.JoinFail ) + if Const.equal c1 c2 then e1 else (L.d_strln "failure reason 29" ; raise Sil.JoinFail) | Exp.Cast (t1, e1), Exp.Cast (t2, e2) -> - if not (Typ.equal t1 t2) then ( L.d_strln "failure reason 30" ; raise Sil.JoinFail ) + if not (Typ.equal t1 t2) then (L.d_strln "failure reason 30" ; raise Sil.JoinFail) else let e1'' = exp_partial_meet e1 e2 in Exp.Cast (t1, e1'') | Exp.UnOp (unop1, e1, topt1), Exp.UnOp (unop2, e2, _) -> - if not (Unop.equal unop1 unop2) then ( L.d_strln "failure reason 31" ; raise Sil.JoinFail ) + if not (Unop.equal unop1 unop2) then (L.d_strln "failure reason 31" ; raise Sil.JoinFail) else Exp.UnOp (unop1, exp_partial_meet e1 e2, topt1) (* should be topt1 = topt2 *) | Exp.BinOp (binop1, e1, e1'), Exp.BinOp (binop2, e2, e2') -> - if not (Binop.equal binop1 binop2) then ( L.d_strln "failure reason 32" ; raise Sil.JoinFail ) + if not (Binop.equal binop1 binop2) then (L.d_strln "failure reason 32" ; raise Sil.JoinFail) else let e1'' = exp_partial_meet e1 e2 in let e2'' = exp_partial_meet e1' e2' in Exp.BinOp (binop1, e1'', e2'') | Exp.Var id, Exp.Lvar _ -> if not (Ident.is_normal id) then Rename.extend e1 e2 (Rename.ExtDefault e2) - else ( L.d_strln "failure reason 33" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 33" ; raise Sil.JoinFail) | Exp.Lvar _, Exp.Var id -> if not (Ident.is_normal id) then Rename.extend e1 e2 (Rename.ExtDefault e1) - else ( L.d_strln "failure reason 34" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 34" ; raise Sil.JoinFail) | Exp.Lvar pvar1, Exp.Lvar pvar2 -> - if not (Pvar.equal pvar1 pvar2) then ( L.d_strln "failure reason 35" ; raise Sil.JoinFail ) + if not (Pvar.equal pvar1 pvar2) then (L.d_strln "failure reason 35" ; raise Sil.JoinFail) else e1 | Exp.Lfield (e1, f1, t1), Exp.Lfield (e2, f2, _) -> - if not (Typ.Fieldname.equal f1 f2) then ( L.d_strln "failure reason 36" ; raise Sil.JoinFail ) + if not (Typ.Fieldname.equal f1 f2) then (L.d_strln "failure reason 36" ; raise Sil.JoinFail) else Exp.Lfield (exp_partial_meet e1 e2, f1, t1) (* should be t1 = t2 *) | Exp.Lindex (e1, e1'), Exp.Lindex (e2, e2') -> let e1'' = exp_partial_meet e1 e2 in @@ -1286,25 +1284,25 @@ let kind_meet k1 k2 = let hpara_partial_join tenv (hpara1 : Sil.hpara) (hpara2 : Sil.hpara) : Sil.hpara = if Match.hpara_match_with_impl tenv true hpara2 hpara1 then hpara1 else if Match.hpara_match_with_impl tenv true hpara1 hpara2 then hpara2 - else ( L.d_strln "failure reason 53" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 53" ; raise Sil.JoinFail) let hpara_partial_meet tenv (hpara1 : Sil.hpara) (hpara2 : Sil.hpara) : Sil.hpara = if Match.hpara_match_with_impl tenv true hpara2 hpara1 then hpara2 else if Match.hpara_match_with_impl tenv true hpara1 hpara2 then hpara1 - else ( L.d_strln "failure reason 54" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 54" ; raise Sil.JoinFail) let hpara_dll_partial_join tenv (hpara1 : Sil.hpara_dll) (hpara2 : Sil.hpara_dll) : Sil.hpara_dll = if Match.hpara_dll_match_with_impl tenv true hpara2 hpara1 then hpara1 else if Match.hpara_dll_match_with_impl tenv true hpara1 hpara2 then hpara2 - else ( L.d_strln "failure reason 55" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 55" ; raise Sil.JoinFail) let hpara_dll_partial_meet tenv (hpara1 : Sil.hpara_dll) (hpara2 : Sil.hpara_dll) : Sil.hpara_dll = if Match.hpara_dll_match_with_impl tenv true hpara2 hpara1 then hpara2 else if Match.hpara_dll_match_with_impl tenv true hpara1 hpara2 then hpara1 - else ( L.d_strln "failure reason 56" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 56" ; raise Sil.JoinFail) (** {2 Join and Meet for hpred} *) @@ -1329,7 +1327,7 @@ let hpred_partial_join tenv mode (todo : Exp.t * Exp.t * Exp.t) (hpred1 : Sil.hp let iF', iB' = if fwd1 && fwd2 then (e, exp_partial_join iB1 iB2) else if (not fwd1) && not fwd2 then (exp_partial_join iF1 iF2, e) - else ( L.d_strln "failure reason 57" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 57" ; raise Sil.JoinFail) in let oF' = exp_partial_join oF1 oF2 in let oB' = exp_partial_join oB1 oB2 in @@ -1339,8 +1337,8 @@ let hpred_partial_join tenv mode (todo : Exp.t * Exp.t * Exp.t) (hpred1 : Sil.hp assert false -let hpred_partial_meet tenv (todo : Exp.t * Exp.t * Exp.t) (hpred1 : Sil.hpred) - (hpred2 : Sil.hpred) : Sil.hpred = +let hpred_partial_meet tenv (todo : Exp.t * Exp.t * Exp.t) (hpred1 : Sil.hpred) (hpred2 : Sil.hpred) + : Sil.hpred = let e1, e2, e = todo in match (hpred1, hpred2) with | Sil.Hpointsto (_, se1, te1), Sil.Hpointsto (_, se2, te2) when Exp.equal te1 te2 -> @@ -1360,7 +1358,7 @@ let hpred_partial_meet tenv (todo : Exp.t * Exp.t * Exp.t) (hpred1 : Sil.hpred) let iF', iB' = if fwd1 && fwd2 then (e, exp_partial_meet iB1 iB2) else if (not fwd1) && not fwd2 then (exp_partial_meet iF1 iF2, e) - else ( L.d_strln "failure reason 59" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 59" ; raise Sil.JoinFail) in let oF' = exp_partial_meet oF1 oF2 in let oB' = exp_partial_meet oB1 oB2 in @@ -1487,7 +1485,7 @@ let rec sigma_partial_join' tenv mode (sigma_acc : Prop.sigma) (sigma1_in : Prop 'side' describes that target is Lhs or Rhs. 'todo' describes the start point. *) let cut_sigma side todo (target : Prop.sigma) (other : Prop.sigma) = - let list_is_empty l = if l <> [] then ( L.d_strln "failure reason 61" ; raise Sil.JoinFail ) in + let list_is_empty l = if l <> [] then (L.d_strln "failure reason 61" ; raise Sil.JoinFail) in let x = Todo.take () in Todo.push todo ; let res = @@ -1550,13 +1548,13 @@ let rec sigma_partial_join' tenv mode (sigma_acc : Prop.sigma) (sigma1_in : Prop if (not Config.nelseg) || Sil.equal_lseg_kind k Sil.Lseg_PE then let sigma_acc' = join_list_and_non Lhs e lseg e1 e2 :: sigma_acc in sigma_partial_join' tenv mode sigma_acc' sigma1 sigma2 - else ( L.d_strln "failure reason 62" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 62" ; raise Sil.JoinFail) | None, Some (Sil.Hlseg (k, _, _, _, _) as lseg) | None, Some (Sil.Hdllseg (k, _, _, _, _, _, _) as lseg) -> if (not Config.nelseg) || Sil.equal_lseg_kind k Sil.Lseg_PE then let sigma_acc' = join_list_and_non Rhs e lseg e2 e1 :: sigma_acc in sigma_partial_join' tenv mode sigma_acc' sigma1 sigma2 - else ( L.d_strln "failure reason 63" ; raise Sil.JoinFail ) + else (L.d_strln "failure reason 63" ; raise Sil.JoinFail) | None, _ | _, None -> L.d_strln "failure reason 64" ; raise Sil.JoinFail | Some hpred1, Some hpred2 when same_pred hpred1 hpred2 -> @@ -1619,7 +1617,7 @@ let sigma_partial_join tenv mode (sigma1 : Prop.sigma) (sigma2 : Prop.sigma) : SymOp.try_finally ~f:(fun () -> if Rename.check lost_little then (s1, s2, s3) - else ( L.d_strln "failed Rename.check" ; raise Sil.JoinFail ) ) + else (L.d_strln "failed Rename.check" ; raise Sil.JoinFail) ) ~finally:CheckJoin.final @@ -1726,9 +1724,7 @@ let pi_partial_join tenv mode (ep1 : Prop.exposed Prop.t) (ep2 : Prop.exposed Pr | None -> None | Some (n, e) -> - let bound = - if IntLit.leq IntLit.minus_one n then IntLit.minus_one else widening_bottom - in + let bound = if IntLit.leq IntLit.minus_one n then IntLit.minus_one else widening_bottom in let a' = Prop.mk_inequality tenv (Exp.BinOp (Binop.Lt, Exp.int bound, e)) in Some a' ) in @@ -1803,12 +1799,12 @@ let pi_partial_join tenv mode (ep1 : Prop.exposed Prop.t) (ep2 : Prop.exposed Pr let p2 = Prop.normalize tenv ep2 in List.fold ~f:(handle_atom_with_widening Lhs p2 pi2) ~init:[] pi1 in - if Config.trace_join then ( L.d_str "atom_list1: " ; Prop.d_pi atom_list1 ; L.d_ln () ) ; + if Config.trace_join then (L.d_str "atom_list1: " ; Prop.d_pi atom_list1 ; L.d_ln ()) ; let atom_list2 = let p1 = Prop.normalize tenv ep1 in List.fold ~f:(handle_atom_with_widening Rhs p1 pi1) ~init:[] pi2 in - if Config.trace_join then ( L.d_str "atom_list2: " ; Prop.d_pi atom_list2 ; L.d_ln () ) ; + if Config.trace_join then (L.d_str "atom_list2: " ; Prop.d_pi atom_list2 ; L.d_ln ()) ; let atom_list_combined = IList.inter ~cmp:Sil.compare_atom atom_list1 atom_list2 in if Config.trace_join then ( L.d_str "atom_list_combined: " ; Prop.d_pi atom_list_combined ; L.d_ln () ) ; @@ -1824,7 +1820,7 @@ let pi_partial_meet tenv (p : Prop.normal Prop.t) (ep1 : 'a Prop.t) (ep2 : 'b Pr let handle_atom sub dom atom = if Sil.atom_free_vars atom |> Sequence.for_all ~f:(fun id -> Ident.Set.mem id dom) then Sil.atom_sub sub atom - else ( L.d_str "handle_atom failed on " ; Sil.d_atom atom ; L.d_ln () ; raise Sil.JoinFail ) + else (L.d_str "handle_atom failed on " ; Sil.d_atom atom ; L.d_ln () ; raise Sil.JoinFail) in let f1 p' atom = Prop.prop_atom_and tenv p' (handle_atom sub1 dom1 atom) in let f2 p' atom = Prop.prop_atom_and tenv p' (handle_atom sub2 dom2 atom) in @@ -1857,7 +1853,7 @@ let eprop_partial_meet tenv (ep1 : 'a Prop.t) (ep2 : 'b Prop.t) : 'c Prop.t = let f e = Exp.free_vars e |> Sequence.for_all ~f:Ident.is_normal in Sil.equal_subst sub1 sub2 && List.for_all ~f range1 in - if not (sub_check ()) then ( L.d_strln "sub_check() failed" ; raise Sil.JoinFail ) + if not (sub_check ()) then (L.d_strln "sub_check() failed" ; raise Sil.JoinFail) else let todos = List.map ~f:(fun x -> (x, x, x)) es in List.iter ~f:Todo.push todos ; @@ -1918,8 +1914,7 @@ let eprop_partial_join' tenv mode (ep1 : Prop.exposed Prop.t) (ep2 : Prop.expose (sub_common_normal, eqs1, eqs2) in if not (simple_check && expensive_check es1 es2) then ( - if not simple_check then L.d_strln "simple_check failed" - else L.d_strln "expensive_check failed" ; + if not simple_check then L.d_strln "simple_check failed" else L.d_strln "expensive_check failed" ; raise Sil.JoinFail ) ; let todos = List.map ~f:(fun x -> (x, x, x)) es1 in List.iter ~f:Todo.push todos ; @@ -1959,10 +1954,8 @@ let footprint_partial_join' tenv (p1 : Prop.normal Prop.t) (p2 : Prop.normal Pro in let sigma_fp = let sigma_fp0 = efp.Prop.sigma in - let f a = - Sil.hpred_free_vars a |> Sequence.exists ~f:(fun a -> not (Ident.is_footprint a)) - in - if List.exists ~f sigma_fp0 then ( L.d_strln "failure reason 66" ; raise Sil.JoinFail ) ; + let f a = Sil.hpred_free_vars a |> Sequence.exists ~f:(fun a -> not (Ident.is_footprint a)) in + if List.exists ~f sigma_fp0 then (L.d_strln "failure reason 66" ; raise Sil.JoinFail) ; sigma_fp0 in let ep1' = Prop.set p1 ~pi_fp ~sigma_fp in diff --git a/infer/src/biabduction/Match.ml b/infer/src/biabduction/Match.ml index 12ce68834..877f8704c 100644 --- a/infer/src/biabduction/Match.ml +++ b/infer/src/biabduction/Match.ml @@ -356,9 +356,7 @@ let rec iter_match_with_impl tenv iter condition sub vars hpat hpats = prop_match_with_impl_sub tenv p condition sub_new vars_leftover hpat_next hpats_rest in let do_para_lseg _ = - let para2_exist_vars, para2_inst = - Sil.hpara_instantiate para2 e_start2 e_end2 es_shared2 - in + let para2_exist_vars, para2_inst = Sil.hpara_instantiate para2 e_start2 e_end2 es_shared2 in (* let allow_impl hpred = {hpred=hpred; flag=hpat.flag} in *) let allow_impl hpred = {hpred; flag= true} in let para2_hpat, para2_hpats = diff --git a/infer/src/biabduction/Paths.ml b/infer/src/biabduction/Paths.ml index a98b3a21d..876c5ea98 100644 --- a/infer/src/biabduction/Paths.ml +++ b/infer/src/biabduction/Paths.ml @@ -168,7 +168,7 @@ end = struct | Pstart (_, stats) -> if not (stats_is_dummy stats) then set_dummy_stats stats | Pnode (_, _, _, path, stats, _) | Pcall (path, _, ExecSkipped _, stats) -> - if not (stats_is_dummy stats) then ( reset_stats path ; set_dummy_stats stats ) + if not (stats_is_dummy stats) then (reset_stats path ; set_dummy_stats stats) | Pjoin (path1, path2, stats) -> if not (stats_is_dummy stats) then ( reset_stats path1 ; reset_stats path2 ; set_dummy_stats stats ) diff --git a/infer/src/biabduction/Prop.ml b/infer/src/biabduction/Prop.ml index 8bef47dfc..173c1a3ea 100644 --- a/infer/src/biabduction/Prop.ml +++ b/infer/src/biabduction/Prop.ml @@ -229,9 +229,7 @@ let get_pure_extended p = (** Print existential quantification *) -let pp_evars f evars = - if evars <> [] then F.fprintf f "exists [%a]. " (Pp.comma_seq Ident.pp) evars - +let pp_evars f evars = if evars <> [] then F.fprintf f "exists [%a]. " (Pp.comma_seq Ident.pp) evars (** Print an hpara in simple mode *) let pp_hpara_simple pe_ env n f pred = @@ -357,8 +355,7 @@ let gen_free_vars {sigma; sigma_fp; sub; pi; pi_fp} = >>= fun () -> sigma_gen_free_vars sigma_fp >>= fun () -> - Sil.subst_gen_free_vars sub - >>= fun () -> pi_gen_free_vars pi >>= fun () -> pi_gen_free_vars pi_fp + Sil.subst_gen_free_vars sub >>= fun () -> pi_gen_free_vars pi >>= fun () -> pi_gen_free_vars pi_fp let free_vars prop = Sequence.Generator.run (gen_free_vars prop) @@ -440,8 +437,7 @@ let rec create_strexp_of_type ~path tenv struct_init_mode (typ : Typ.t) len inst let init_value () = let create_fresh_var () = let fresh_id = - Ident.create_fresh - (if !BiabductionConfig.footprint then Ident.kfootprint else Ident.kprimed) + Ident.create_fresh (if !BiabductionConfig.footprint then Ident.kfootprint else Ident.kprimed) in Exp.Var fresh_id in @@ -455,8 +451,8 @@ let rec create_strexp_of_type ~path tenv struct_init_mode (typ : Typ.t) len inst | Tstruct name, _ -> ( if List.exists ~f:(fun (n, _) -> Typ.Name.equal n name) path then L.die InternalError - "Ill-founded recursion in [create_strexp_of_type]: a sub-element of struct %a is also \ - of type struct %a: %a:%a" + "Ill-founded recursion in [create_strexp_of_type]: a sub-element of struct %a is also of \ + type struct %a: %a:%a" Typ.Name.pp name Typ.Name.pp name pp_path (List.rev path) Typ.Name.pp name ; match (struct_init_mode, Tenv.lookup tenv name) with | Fld_init, Some {fields} -> @@ -831,7 +827,7 @@ module Normalize = struct in match (e1', e2') with (* pattern for arrays and extensible structs: - sizeof(struct s {... t[l]}) + k * sizeof(t)) = sizeof(struct s {... t[l + k]}) *) + sizeof(struct s {... t[l]}) + k * sizeof(t)) = sizeof(struct s {... t[l + k]}) *) | ( Sizeof ({typ; dynamic_length= len1_opt} as sizeof_data) , BinOp (Mult _, len2, Sizeof {typ= elt; dynamic_length= None}) ) when isPlusA && extensible_array_element_typ_equal elt typ -> @@ -1457,7 +1453,7 @@ module Normalize = struct match (normalized_cnt, normalized_te) with | Earray ((Exp.Sizeof _ as size), [], inst), Sizeof {typ= {desc= Tarray _}} -> (* check for an empty array whose size expression is (Sizeof type), and turn the array - into a strexp of the given type *) + into a strexp of the given type *) let hpred' = mk_ptsto_exp tenv Fld_init (root, size, None) inst in replace_hpred hpred' | ( Earray @@ -1481,10 +1477,7 @@ module Normalize = struct , Sizeof {typ= {desc= Tarray {elt}} as arr} ) when Typ.equal typ elt -> let sizeof_data = - { Exp.typ= arr - ; nbytes= None - ; dynamic_length= Some (Exp.BinOp (omult, x, len)) - ; subtype } + {Exp.typ= arr; nbytes= None; dynamic_length= Some (Exp.BinOp (omult, x, len)); subtype} in let hpred' = mk_ptsto_exp tenv Fld_init (root, Sizeof sizeof_data, None) inst in replace_hpred (replace_array_contents hpred' esel) @@ -1495,10 +1488,7 @@ module Normalize = struct , Sizeof {typ= {desc= Tarray {elt}} as arr} ) when Typ.equal typ elt -> let sizeof_data = - { Exp.typ= arr - ; nbytes= None - ; dynamic_length= Some (Exp.BinOp (omult, x, len)) - ; subtype } + {Exp.typ= arr; nbytes= None; dynamic_length= Some (Exp.BinOp (omult, x, len)); subtype} in let hpred' = mk_ptsto_exp tenv Fld_init (root, Sizeof sizeof_data, None) inst in replace_hpred (replace_array_contents hpred' esel) @@ -1553,9 +1543,7 @@ module Normalize = struct in List.fold ~f:get_disequality_info ~init:[] nonineq_list in - let is_neq e n = - List.exists ~f:(fun (e', n') -> Exp.equal e e' && IntLit.eq n n') diseq_list - in + let is_neq e n = List.exists ~f:(fun (e', n') -> Exp.equal e e' && IntLit.eq n n') diseq_list in let le_list_tightened = let get_le_inequality_info acc a = match atom_exp_le_const a with Some (e, n) -> (e, n) :: acc | _ -> acc diff --git a/infer/src/biabduction/Prop.mli b/infer/src/biabduction/Prop.mli index 809ff3ce4..e489a8b75 100644 --- a/infer/src/biabduction/Prop.mli +++ b/infer/src/biabduction/Prop.mli @@ -193,8 +193,7 @@ val mk_ptsto_exp : Tenv.t -> struct_init_mode -> Exp.t * Exp.t * Exp.t option -> (** Construct a points-to predicate for an expression using either the provided expression [name] as base for fresh identifiers. *) -val mk_ptsto_lvar : - Tenv.t -> struct_init_mode -> Sil.inst -> Pvar.t * Exp.t * Exp.t option -> hpred +val mk_ptsto_lvar : Tenv.t -> struct_init_mode -> Sil.inst -> Pvar.t * Exp.t * Exp.t option -> hpred (** Construct a points-to predicate for a single program variable. If [expand_structs] is true, initialize the fields of structs with fresh variables. *) diff --git a/infer/src/biabduction/Propgraph.mli b/infer/src/biabduction/Propgraph.mli index 28a365709..16818f74b 100644 --- a/infer/src/biabduction/Propgraph.mli +++ b/infer/src/biabduction/Propgraph.mli @@ -27,8 +27,7 @@ val diff_get_colormap : bool -> 'a diff -> Pp.colormap (** [diff_get_colormap footprint_part diff] returns the colormap of a computed diff, selecting the footprint colormap if [footprint_part] is true. *) -val pp_proplist : - Pp.env -> string -> 'a Prop.t * bool -> Format.formatter -> 'b Prop.t list -> unit +val pp_proplist : Pp.env -> string -> 'a Prop.t * bool -> Format.formatter -> 'b Prop.t list -> unit (** Print a list of propositions, prepending each one with the given string, If !Config.pring_using_diff is true, print the diff w.r.t. the given prop, extracting its local stack vars if the boolean is true. *) diff --git a/infer/src/biabduction/Prover.ml b/infer/src/biabduction/Prover.ml index b9edb60a8..352fdb32e 100644 --- a/infer/src/biabduction/Prover.ml +++ b/infer/src/biabduction/Prover.ml @@ -145,9 +145,7 @@ end = struct let sort_then_remove_redundancy constraints = let constraints_sorted = List.sort ~compare constraints in - let have_same_key (e1, e2, _) (f1, f2, _) = - [%compare.equal: Exp.t * Exp.t] (e1, e2) (f1, f2) - in + let have_same_key (e1, e2, _) (f1, f2, _) = [%compare.equal: Exp.t * Exp.t] (e1, e2) (f1, f2) in remove_redundancy have_same_key [] constraints_sorted @@ -548,9 +546,7 @@ end = struct leqs in let upper_list = - List.map - ~f:(function _, Exp.Const (Const.Cint n) -> n | _ -> assert false) - e_upper_list + List.map ~f:(function _, Exp.Const (Const.Cint n) -> n | _ -> assert false) e_upper_list in if List.is_empty upper_list then None else Some (compute_min_from_nonempty_int_list upper_list) @@ -572,9 +568,7 @@ end = struct lts in let lower_list = - List.map - ~f:(function Exp.Const (Const.Cint n), _ -> n | _ -> assert false) - e_lower_list + List.map ~f:(function Exp.Const (Const.Cint n), _ -> n | _ -> assert false) e_lower_list in if List.is_empty lower_list then None else Some (compute_max_from_nonempty_int_list lower_list) @@ -1215,8 +1209,8 @@ end = struct L.d_decrease_indent () ; if !missing_pi <> [] && !missing_sigma <> [] then ( L.d_ln () ; Prop.d_pi !missing_pi ; L.d_strln "*" ; Prop.d_sigma !missing_sigma ) - else if !missing_pi <> [] then ( L.d_ln () ; Prop.d_pi !missing_pi ) - else if !missing_sigma <> [] then ( L.d_ln () ; Prop.d_sigma !missing_sigma ) ; + else if !missing_pi <> [] then (L.d_ln () ; Prop.d_pi !missing_pi) + else if !missing_sigma <> [] then (L.d_ln () ; Prop.d_sigma !missing_sigma) ; if !missing_fld <> [] then ( L.d_ln () ; L.d_strln "MISSING FLD:" ; @@ -1498,9 +1492,7 @@ let rec sexp_imply tenv source calc_index_frame calc_missing subs se1 se2 typ2 : let subs', fld_frame, fld_missing = struct_imply tenv source calc_missing subs fsel1 fsel2 typ2 in - let fld_frame_opt = - if fld_frame <> [] then Some (Sil.Estruct (fld_frame, inst1)) else None - in + let fld_frame_opt = if fld_frame <> [] then Some (Sil.Estruct (fld_frame, inst1)) else None in let fld_missing_opt = if fld_missing <> [] then Some (Sil.Estruct (fld_missing, inst1)) else None in @@ -1768,7 +1760,7 @@ let expand_hpred_pointer = match cnt_texp with | Sizeof ({typ= cnt_typ} as sizeof_data) -> (* type of struct at adr_base is unknown (typically Tvoid), but - type of contents is known, so construct struct type for single fld:cnt_typ *) + type of contents is known, so construct struct type for single fld:cnt_typ *) let name = Typ.Name.C.from_string ("counterfeit" ^ string_of_int !count) in incr count ; let fields = [(fld, cnt_typ, Annot.Item.empty)] in @@ -1776,12 +1768,10 @@ let expand_hpred_pointer = Exp.Sizeof {sizeof_data with typ= Typ.mk (Tstruct name)} | _ -> (* type of struct at adr_base and of contents are both unknown: give up *) - L.(die InternalError) - "expand_hpred_pointer: Unexpected non-sizeof type in Lfield" ) - in - let hpred' = - Sil.Hpointsto (adr_base, Estruct ([(fld, cnt)], Sil.inst_none), cnt_texp') + L.(die InternalError) "expand_hpred_pointer: Unexpected non-sizeof type in Lfield" + ) in + let hpred' = Sil.Hpointsto (adr_base, Estruct ([(fld, cnt)], Sil.inst_none), cnt_texp') in expand true true hpred' | Sil.Hpointsto (Exp.Lindex (e, ind), se, t) -> let t' = @@ -2074,9 +2064,7 @@ let rec hpred_imply tenv calc_index_frame calc_missing subs prop1 sigma2 hpred2 | Sil.Hpointsto (e1, se1, texp1), _ -> ( try let typ2 = Exp.texp_to_typ (Some (Typ.mk Tvoid)) texp2 in - let typing_frame, typing_missing = - texp_imply tenv subs texp1 texp2 e1 calc_missing - in + let typing_frame, typing_missing = texp_imply tenv subs texp1 texp2 e1 calc_missing in let se1' = sexp_imply_preprocess se1 texp1 se2 in let subs', fld_frame, fld_missing = sexp_imply tenv e1 calc_index_frame calc_missing subs se1' se2 typ2 @@ -2284,8 +2272,7 @@ let rec hpred_imply tenv calc_index_frame calc_missing subs prop1 sigma2 hpred2 instantiations for the primed variables of [sigma1] and [sigma2] and a frame. Raise IMPL_FALSE if the implication cannot be proven. *) -and sigma_imply tenv calc_index_frame calc_missing subs prop1 sigma2 : subst2 * Prop.normal Prop.t - = +and sigma_imply tenv calc_index_frame calc_missing subs prop1 sigma2 : subst2 * Prop.normal Prop.t = let is_constant_string_class subs = function (* if the hpred represents a constant string, return the string *) | Sil.Hpointsto (e2_, _, _) -> ( @@ -2556,7 +2543,7 @@ let check_implication_base pname tenv check_frame_empty calc_missing prop1 prop2 Prop.d_pi pi2 ; L.d_decrease_indent () ; L.d_ln () ; - if pi2_bcheck <> [] then ( L.d_str "pi2 bounds checks: " ; Prop.d_pi pi2_bcheck ; L.d_ln () ) ; + if pi2_bcheck <> [] then (L.d_str "pi2 bounds checks: " ; Prop.d_pi pi2_bcheck ; L.d_ln ()) ; L.d_strln "returns" ; L.d_strln "sub1:" ; L.d_increase_indent () ; @@ -2695,8 +2682,7 @@ let find_minimum_pure_cover tenv cases = | [] -> seen | (pi, x) :: todo' -> - if is_cover tenv (seen @ todo') then shrink_ seen todo' - else shrink_ ((pi, x) :: seen) todo' + if is_cover tenv (seen @ todo') then shrink_ seen todo' else shrink_ ((pi, x) :: seen) todo' in let shrink cases = if List.length cases > 2 then shrink_ [] cases else cases in try Some (shrink (grow [] cases)) with NO_COVER -> None diff --git a/infer/src/biabduction/Rearrange.ml b/infer/src/biabduction/Rearrange.ml index 99141c429..27ea2baf0 100644 --- a/infer/src/biabduction/Rearrange.ml +++ b/infer/src/biabduction/Rearrange.ml @@ -15,9 +15,7 @@ module L = Logging let list_product l1 l2 = let l1' = List.rev l1 in let l2' = List.rev l2 in - List.fold - ~f:(fun acc x -> List.fold ~f:(fun acc' y -> (x, y) :: acc') ~init:acc l2') - ~init:[] l1' + List.fold ~f:(fun acc x -> List.fold ~f:(fun acc' y -> (x, y) :: acc') ~init:acc l2') ~init:[] l1' let rec list_rev_and_concat l1 l2 = @@ -44,7 +42,7 @@ let check_bad_index tenv pname p len index loc = let index_nonnegative = Prop.mk_inequality tenv (Exp.BinOp (Binop.Le, Exp.zero, index)) in Prover.check_zero tenv index || (* index 0 always in bound, even when we know nothing about len *) - (Prover.check_atom tenv p index_not_too_large && Prover.check_atom tenv p index_nonnegative) + (Prover.check_atom tenv p index_not_too_large && Prover.check_atom tenv p index_nonnegative) in let index_has_bounds () = match Prover.get_bounds tenv p index with Some _, Some _ -> true | _ -> false @@ -208,8 +206,8 @@ let rec strexp_extend_values_ pname tenv orig_prop footprint_part kind max_stamp match List.find ~f:(fun (f', _) -> Typ.Fieldname.equal f f') fsel with | Some (_, se') -> let atoms_se_typ_list' = - strexp_extend_values_ pname tenv orig_prop footprint_part kind max_stamp se' typ' - off' inst + strexp_extend_values_ pname tenv orig_prop footprint_part kind max_stamp se' typ' off' + inst in let replace acc (res_atoms', res_se', res_typ') = let replace_fse ((f1, _) as ft1) = @@ -231,8 +229,7 @@ let rec strexp_extend_values_ pname tenv orig_prop footprint_part kind max_stamp List.fold ~f:replace ~init:[] atoms_se_typ_list' | None -> let atoms', se', res_typ' = - create_struct_values pname tenv orig_prop footprint_part kind max_stamp typ' off' - inst + create_struct_values pname tenv orig_prop footprint_part kind max_stamp typ' off' inst in let res_fsel' = List.sort ~compare:[%compare: Typ.Fieldname.t * Sil.strexp] ((f, se') :: fsel) @@ -345,8 +342,8 @@ and array_case_analysis_index pname tenv orig_prop footprint_part kind max_stamp List.concat (List.rev (res_new :: acc)) | ((i, se) as ise) :: isel_unseen -> let atoms_se_typ_list = - strexp_extend_values_ pname tenv orig_prop footprint_part kind max_stamp se typ_cont - off inst + strexp_extend_values_ pname tenv orig_prop footprint_part kind max_stamp se typ_cont off + inst in let atoms_se_typ_list' = List.fold @@ -413,9 +410,7 @@ let strexp_extend_values pname tenv orig_prop footprint_part kind max_stamp se t strexp_extend_values_ pname tenv orig_prop footprint_part kind max_stamp se typ off' inst in let atoms_se_typ_list_filtered = - let check_neg_atom atom = - Prover.check_atom tenv Prop.prop_emp (Prover.atom_negate tenv atom) - in + let check_neg_atom atom = Prover.check_atom tenv Prop.prop_emp (Prover.atom_negate tenv atom) in let check_not_inconsistent (atoms, _, _) = not (List.exists ~f:check_neg_atom atoms) in List.filter ~f:check_not_inconsistent atoms_se_typ_list in @@ -446,7 +441,7 @@ let mk_ptsto_exp_footprint pname tenv orig_prop (lexp, typ) max_stamp inst : if not (exp_has_only_footprint_ids root) then if (* in angelic mode, purposely ignore dangling pointer warnings during the footprint phase -- we - * will fix them during the re - execution phase *) + * will fix them during the re - execution phase *) not !BiabductionConfig.footprint then ( L.internal_error "!!!! Footprint Error, Bad Root : %a !!!! @\n" Exp.pp lexp ; @@ -474,16 +469,16 @@ let mk_ptsto_exp_footprint pname tenv orig_prop (lexp, typ) max_stamp inst : off0 inst in ( atoms - , Prop.mk_ptsto tenv root se - (Exp.Sizeof {typ; nbytes= None; dynamic_length= None; subtype}) ) + , Prop.mk_ptsto tenv root se (Exp.Sizeof {typ; nbytes= None; dynamic_length= None; subtype}) + ) | _ -> let atoms, se, typ = create_struct_values pname tenv orig_prop footprint_part Ident.kfootprint max_stamp typ off0 inst in ( atoms - , Prop.mk_ptsto tenv root se - (Exp.Sizeof {typ; nbytes= None; dynamic_length= None; subtype}) ) + , Prop.mk_ptsto tenv root se (Exp.Sizeof {typ; nbytes= None; dynamic_length= None; subtype}) + ) in let atoms, ptsto_foot = create_ptsto true off_foot in let sub = Sil.subst_of_list eqs in @@ -688,9 +683,7 @@ let prop_iter_add_hpred_footprint_to_prop pname tenv prop (lexp, typ) inst = let nsigma_fp = Prop.sigma_normalize_prop tenv Prop.prop_emp sigma_fp in let prop' = Prop.normalize tenv (Prop.set eprop ~sigma_fp:nsigma_fp) in let prop_new = - List.fold - ~f:(Prop.prop_atom_and tenv ~footprint:!BiabductionConfig.footprint) - ~init:prop' atoms + List.fold ~f:(Prop.prop_atom_and tenv ~footprint:!BiabductionConfig.footprint) ~init:prop' atoms in let iter = match Prop.prop_iter_create prop_new with @@ -849,8 +842,8 @@ let add_guarded_by_constraints tenv prop lexp pdesc = match get_fld_strexp_and_typ typ (is_guarded_by_fld guarded_by_str0) flds with | None when guarded_by_str_is_this guarded_by_str0 -> (* if the guarded-by string is "OuterClass.this", look for "this$n" for some n. - note that this is a bit sketchy when there are mutliple this$n's, but there's - nothing we can do to disambiguate them. *) + note that this is a bit sketchy when there are mutliple this$n's, but there's + nothing we can do to disambiguate them. *) get_fld_strexp_and_typ typ (fun f _ -> Typ.Fieldname.Java.is_outer_instance f) flds | None -> (* can't find an exact match. try a different convention. *) @@ -919,9 +912,9 @@ let add_guarded_by_constraints tenv prop lexp pdesc = | _ -> false ) || (* or the prop says we already have the lock *) - List.exists - ~f:(function Sil.Apred (Alocked, _) -> true | _ -> false) - (Attribute.get_for_exp tenv prop guarded_by_exp) + List.exists + ~f:(function Sil.Apred (Alocked, _) -> true | _ -> false) + (Attribute.get_for_exp tenv prop guarded_by_exp) in let guardedby_is_self_referential = String.equal "itself" (String.lowercase guarded_by_str) @@ -1237,8 +1230,8 @@ let iter_rearrange_pe_lseg tenv recurse_on_iters default_case_iter iter para e1 (** do re-arrangment for an iter whose current element is a possibly empty dllseg to be unrolled from lhs *) -let iter_rearrange_pe_dllseg_first tenv recurse_on_iters default_case_iter iter para_dll e1 e2 e3 - e4 elist = +let iter_rearrange_pe_dllseg_first tenv recurse_on_iters default_case_iter iter para_dll e1 e2 e3 e4 + elist = let iter_inductive_case = let n' = Exp.Var (Ident.create_fresh Ident.kprimed) in let _, para_dll_inst1 = Sil.hpara_dll_instantiate para_dll e1 e2 n' elist in @@ -1407,8 +1400,7 @@ let rec iter_rearrange pname tenv lexp typ_from_instr prop iter inst : let f_one_iter iter' = let prop' = Prop.prop_iter_to_prop tenv iter' in if Prover.check_inconsistency tenv prop' then [] - else - iter_rearrange pname tenv (Prop.lexp_normalize_prop tenv prop' lexp) typ prop' iter' inst + else iter_rearrange pname tenv (Prop.lexp_normalize_prop tenv prop' lexp) typ prop' iter' inst in let rec f_many_iters iters_lst = function | [] -> @@ -1626,9 +1618,7 @@ let check_dereference_error tenv pdesc (prop : Prop.normal Prop.t) lexp loc = match attribute_opt with | Some (Apred (Adangling dk, _)) -> let deref_str = Localise.deref_str_dangling (Some dk) in - let err_desc = - Errdesc.explain_dereference pname tenv deref_str prop (State.get_loc_exn ()) - in + let err_desc = Errdesc.explain_dereference pname tenv deref_str prop (State.get_loc_exn ()) in raise (Exceptions.Dangling_pointer_dereference (Some dk, err_desc, __POS__)) | Some (Apred (Aundef _, _)) -> () @@ -1730,7 +1720,7 @@ let check_call_to_objc_block_error tenv pdesc prop fun_exp loc = warn err_desc_nobuckets ) | _ -> (* HP: fun_exp is not a footprint therefore, - either is a local or it's a modified param *) + either is a local or it's a modified param *) let err_desc = Localise.error_desc_set_bucket err_desc_nobuckets Localise.BucketLevel.b1 in raise (Exceptions.Null_dereference (err_desc, __POS__)) diff --git a/infer/src/biabduction/Rearrange.mli b/infer/src/biabduction/Rearrange.mli index 409b9ec54..b3383485f 100644 --- a/infer/src/biabduction/Rearrange.mli +++ b/infer/src/biabduction/Rearrange.mli @@ -13,8 +13,7 @@ open! IStd exception (* TODO: this description is not clear *) ARRAY_ACCESS -val is_only_pt_by_fld_or_param_nonnull : - Procdesc.t -> Tenv.t -> Prop.normal Prop.t -> Exp.t -> bool +val is_only_pt_by_fld_or_param_nonnull : Procdesc.t -> Tenv.t -> Prop.normal Prop.t -> Exp.t -> bool val check_dereference_error : Tenv.t -> Procdesc.t -> Prop.normal Prop.t -> Exp.t -> Location.t -> unit diff --git a/infer/src/biabduction/RetainCyclesType.ml b/infer/src/biabduction/RetainCyclesType.ml index 03b7d8055..cf658f9fc 100644 --- a/infer/src/biabduction/RetainCyclesType.ml +++ b/infer/src/biabduction/RetainCyclesType.ml @@ -142,16 +142,15 @@ let create_cycle cycle = (*isa is an internal field not accessible or writable, so it doesn't make sense in a cycle *) if List.exists ~f:is_isa_field cycle then None (* The modelled types, where the models are meant to catch NPEs or Memory Leaks, include fields - that don't necessarily reflect the real code, so potential retain cycles including them are - probably wrong. *) + that don't necessarily reflect the real code, so potential retain cycles including them are + probably wrong. *) else if List.exists ~f:is_modelled_type cycle then None (* There are some false positives where we report on null expressions, we can eliminate them here *) else if List.exists ~f:is_exp_null cycle then None else match cycle with | [hd] -> - if is_inst_rearrange hd then None - (* cycles of length 1 created at rearrange are not real *) + if is_inst_rearrange hd then None (* cycles of length 1 created at rearrange are not real *) else Some (normalize_cycle {rc_elements= cycle; rc_head= hd}) | hd :: _ -> Some (normalize_cycle {rc_elements= cycle; rc_head= hd}) @@ -184,8 +183,8 @@ let pp_dotty fmt cycle = Format.fprintf fmt "" in let pp_dotty_element fmt element = - Format.fprintf fmt "\t\"%a\" [label = \"%a | %a \"]@\n" pp_dotty_id element pp_dotty_obj - element pp_dotty_field element + Format.fprintf fmt "\t\"%a\" [label = \"%a | %a \"]@\n" pp_dotty_id element pp_dotty_obj element + pp_dotty_field element in let rec pp_dotty_edges fmt edges = match edges with diff --git a/infer/src/biabduction/RetainCyclesType.mli b/infer/src/biabduction/RetainCyclesType.mli index 7c4c28283..0b79396ab 100644 --- a/infer/src/biabduction/RetainCyclesType.mli +++ b/infer/src/biabduction/RetainCyclesType.mli @@ -19,8 +19,8 @@ type retain_cycle_edge = Object of retain_cycle_edge_obj | Block of Typ.Procname to model the cycle structure. The next element from the end of the list is the head. *) type t = {rc_head: retain_cycle_edge; rc_elements: retain_cycle_edge list} -(** Set for retain cycles. *) module Set : Caml.Set.S with type elt = t +(** Set for retain cycles. *) val d_retain_cycle : t -> unit diff --git a/infer/src/biabduction/State.ml b/infer/src/biabduction/State.ml index 15cd5df14..1ccc939e1 100644 --- a/infer/src/biabduction/State.ml +++ b/infer/src/biabduction/State.ml @@ -260,12 +260,7 @@ let mark_instr_fail exn = type log_issue = - Typ.Procname.t - -> ?node:Procdesc.Node.t - -> ?loc:Location.t - -> ?ltr:Errlog.loc_trace - -> exn - -> unit + Typ.Procname.t -> ?node:Procdesc.Node.t -> ?loc:Location.t -> ?ltr:Errlog.loc_trace -> exn -> unit let process_execution_failures (log_issue : log_issue) pname = let do_failure _ fs = diff --git a/infer/src/biabduction/State.mli b/infer/src/biabduction/State.mli index 5b7757d3a..d8845ee93 100644 --- a/infer/src/biabduction/State.mli +++ b/infer/src/biabduction/State.mli @@ -78,12 +78,7 @@ val mk_find_duplicate_nodes : Procdesc.t -> Procdesc.Node.t -> Procdesc.NodeSet. and normalized (w.r.t. renaming of let - bound ids) list of instructions. *) type log_issue = - Typ.Procname.t - -> ?node:Procdesc.Node.t - -> ?loc:Location.t - -> ?ltr:Errlog.loc_trace - -> exn - -> unit + Typ.Procname.t -> ?node:Procdesc.Node.t -> ?loc:Location.t -> ?ltr:Errlog.loc_trace -> exn -> unit val process_execution_failures : log_issue -> Typ.Procname.t -> unit (** Process the failures during symbolic execution of a procedure *) diff --git a/infer/src/biabduction/SymExec.ml b/infer/src/biabduction/SymExec.ml index 16355a503..b721ad29c 100644 --- a/infer/src/biabduction/SymExec.ml +++ b/infer/src/biabduction/SymExec.ml @@ -112,8 +112,8 @@ let rec apply_offlist pdesc tenv p fp_root nullify_struct (root_lexp, strexp, ty match List.find ~f:(fun fse -> Typ.Fieldname.equal fld (fst fse)) fsel with | Some (_, se') -> let res_e', res_se', res_t', res_pred_insts_op' = - apply_offlist pdesc tenv p fp_root nullify_struct (root_lexp, se', t') offlist' f - inst lookup_inst + apply_offlist pdesc tenv p fp_root nullify_struct (root_lexp, se', t') offlist' f inst + lookup_inst in let replace_fse fse = if Typ.Fieldname.equal fld (fst fse) then (fld, res_se') else fse @@ -127,7 +127,7 @@ let rec apply_offlist pdesc tenv p fp_root nullify_struct (root_lexp, strexp, ty (res_e', res_se, typ, res_pred_insts_op') | None -> (* This case should not happen. The rearrangement should - have materialized all the accessed cells. *) + have materialized all the accessed cells. *) pp_error () ; assert false ) | None -> @@ -146,9 +146,7 @@ let rec apply_offlist pdesc tenv p fp_root nullify_struct (root_lexp, strexp, ty apply_offlist pdesc tenv p fp_root nullify_struct (root_lexp, se', t') offlist' f inst lookup_inst in - let replace_ese ese = - if Exp.equal idx_ese' (fst ese) then (idx_ese', res_se') else ese - in + let replace_ese ese = if Exp.equal idx_ese' (fst ese) then (idx_ese', res_se') else ese in let res_se = Sil.Earray (len, List.map ~f:replace_ese esel, inst1) in let res_t = Typ.mk_array ~default:typ res_t' ?length:len' ?stride:stride' in (res_e', res_se, res_t, res_pred_insts_op') @@ -256,8 +254,7 @@ let prune_ne tenv ~positive e1 e2 prop = *) let prune_ineq tenv ~is_strict ~positive prop e1 e2 = if Exp.equal e1 e2 then - if (positive && not is_strict) || ((not positive) && is_strict) then - Propset.singleton tenv prop + if (positive && not is_strict) || ((not positive) && is_strict) then Propset.singleton tenv prop else Propset.empty else (* build the pruning condition and its negation, as explained in @@ -513,8 +510,8 @@ let method_exists right_proc_name methods = List.exists ~f:(fun meth_name -> Typ.Procname.equal right_proc_name meth_name) methods else (* ObjC/C++ case : The attribute map will only exist when we have code for the method or - the method has been called directly somewhere. It can still be that this is not the - case but we have a model for the method. *) + the method has been called directly somewhere. It can still be that this is not the + case but we have a model for the method. *) match Attributes.load right_proc_name with | Some attrs -> attrs.ProcAttributes.is_defined @@ -806,8 +803,8 @@ let force_objc_init_return_nil pdesc callee_pname tenv ret_id pre path receiver (* 2. We don't know, but obj could be null, we return both options, *) (* (obj = null, res = null), (obj != null, res = [obj foo]) *) (* We want the same behavior even when we are going to skip the function. *) -let handle_objc_instance_method_call_or_skip pdesc tenv actual_pars path callee_pname pre ret_id - res = +let handle_objc_instance_method_call_or_skip pdesc tenv actual_pars path callee_pname pre ret_id res + = let path_description = F.sprintf "Message %s with receiver nil returns nil." (Typ.Procname.to_simplified_string callee_pname) @@ -924,8 +921,8 @@ let is_rec_call callee_pname caller_pdesc = Typ.Procname.equal callee_pname (Procdesc.get_proc_name caller_pdesc) -let add_constraints_on_retval tenv pdesc prop ret_exp ~has_nonnull_annot typ callee_pname - callee_loc = +let add_constraints_on_retval tenv pdesc prop ret_exp ~has_nonnull_annot typ callee_pname callee_loc + = if Typ.Procname.is_infer_undefined callee_pname then prop else let lookup_abduced_expression p abduced_ret_pv = @@ -1098,8 +1095,8 @@ let is_variadic_procname callee_pname = ~default:false -let resolve_and_analyze_no_dynamic_dispatch current_summary tenv prop_r n_actual_params - callee_pname call_flags = +let resolve_and_analyze_no_dynamic_dispatch current_summary tenv prop_r n_actual_params callee_pname + call_flags = let resolved_pname = match resolve_virtual_pname tenv prop_r n_actual_params callee_pname call_flags with | resolved_pname :: _ -> @@ -1148,8 +1145,7 @@ let resolve_and_analyze_clang current_summary tenv prop_r n_actual_params callee callee_pname call_flags in { result with - dynamic_dispatch_status= Some EventLogger.Dynamic_dispatch_model_specialization_failure - } + dynamic_dispatch_status= Some EventLogger.Dynamic_dispatch_model_specialization_failure } else resolve_and_analyze_result with SpecializeProcdesc.UnmatchedParameters -> let result = @@ -1159,8 +1155,8 @@ let resolve_and_analyze_clang current_summary tenv prop_r n_actual_params callee { result with dynamic_dispatch_status= Some EventLogger.Dynamic_dispatch_parameters_arguments_mismatch } else - resolve_and_analyze_no_dynamic_dispatch current_summary tenv prop_r n_actual_params - callee_pname call_flags + resolve_and_analyze_no_dynamic_dispatch current_summary tenv prop_r n_actual_params callee_pname + call_flags let declare_locals_and_ret tenv pdesc (prop_ : Prop.normal Prop.t) = @@ -1250,8 +1246,8 @@ let rec sym_exec exe_env tenv current_summary instr_ (prop_ : Prop.normal Prop.t ; exe_env } in if is_objc_instance_method then - handle_objc_instance_method_call_or_skip current_pdesc tenv actual_args path callee_pname - prop (fst ret_id_typ) skip_res + handle_objc_instance_method_call_or_skip current_pdesc tenv actual_args path callee_pname prop + (fst ret_id_typ) skip_res else skip_res () in let call_args prop_ proc_name args ret_id_typ loc = @@ -1274,8 +1270,7 @@ let rec sym_exec exe_env tenv current_summary instr_ (prop_ : Prop.normal Prop.t | Sil.Prune (cond, loc, true_branch, ik) -> let prop__ = Attribute.nullify_exp_with_objc_null tenv prop_ cond in let check_condition_always_true_false () = - if - !Language.curr_language <> Language.Clang || Config.report_condition_always_true_in_clang + if !Language.curr_language <> Language.Clang || Config.report_condition_always_true_in_clang then let report_condition_always_true_false i = let skip_loop = @@ -1583,11 +1578,8 @@ and add_constraints_on_actuals_by_ref tenv caller_pdesc prop actuals_by_ref call let already_has_abduced_retval p = List.exists ~f:(fun hpred -> - match hpred with - | Sil.Hpointsto (Exp.Lvar pv, _, _) -> - Pvar.equal pv abduced - | _ -> - false ) + match hpred with Sil.Hpointsto (Exp.Lvar pv, _, _) -> Pvar.equal pv abduced | _ -> false + ) p.Prop.sigma_fp in (* prevent introducing multiple abduced retvals for a single call site in a loop *) @@ -1704,8 +1696,7 @@ and unknown_or_scan_call ~is_scan ~reason ret_typ ret_annots match actual with | (Exp.Lvar _ as e), ({Typ.desc= Tptr _} as t) -> Some (e, t, i) - | (Exp.Var _ as e), ({Typ.desc= Tptr _} as t) when should_abduce_param_value callee_pname - -> + | (Exp.Var _ as e), ({Typ.desc= Tptr _} as t) when should_abduce_param_value callee_pname -> Some (e, t, i) | _ -> None ) @@ -1821,8 +1812,7 @@ and sym_exec_objc_setter field _ tenv _ pdesc pname loc args prop = :: (lexp2, typ2) :: _ -> Tenv.add_field tenv struct_name field ; let field_access_exp = Exp.Lfield (lexp1, field_name, typ1) in - execute_store ~report_deref_errors:false pname pdesc tenv field_access_exp typ2 lexp2 loc - prop + execute_store ~report_deref_errors:false pname pdesc tenv field_access_exp typ2 lexp2 loc prop | _ -> raise (Exceptions.Wrong_argument_number __POS__) @@ -1909,12 +1899,12 @@ and proc_call ?dynamic_dispatch exe_env callee_summary raise (Exceptions.Wrong_argument_number __POS__) in (* Actual parameters are associated to their formal - parameter type if there are enough formal parameters, and - to their actual type otherwise. The latter case happens - with variable - arguments functions *) + parameter type if there are enough formal parameters, and + to their actual type otherwise. The latter case happens + with variable - arguments functions *) let actual_params = comb actual_pars formal_types in (* In case we call an objc instance method we add an extra spec - where the receiver is null and the semantics of the call is nop *) + where the receiver is null and the semantics of the call is nop *) let pdesc = Summary.get_proc_desc summary in match (!Language.curr_language, callee_attrs.ProcAttributes.clang_method_kind) with | Language.Clang, ClangMethodKind.OBJC_INSTANCE -> @@ -2030,7 +2020,7 @@ let node handle_exn exe_env tenv summary proc_cfg (node : ProcCfg.Exceptional.No && (not (Sil.instr_is_auxiliary instr)) && ProcCfg.Exceptional.Node.kind node <> Procdesc.Node.exn_handler_kind (* skip normal instructions if an exception was thrown, - unless this is an exception handler node *) + unless this is an exception handler node *) then ( L.d_str "Skipping instr " ; Sil.d_instr instr ; diff --git a/infer/src/biabduction/SymExecBlocks.ml b/infer/src/biabduction/SymExecBlocks.ml index fdc5c22c1..e56e66aa5 100644 --- a/infer/src/biabduction/SymExecBlocks.ml +++ b/infer/src/biabduction/SymExecBlocks.ml @@ -58,7 +58,7 @@ let resolve_method_with_block_args_and_analyze ~caller_summary pname act_params (* only specialize defined methods, and when formals and actuals have the same length *) -> ( (* a list with the same length of the actual params of the function, - containing either a Closure or None. *) + containing either a Closure or None. *) let block_args = List.map act_params ~f:(function | Exp.Closure cl, _ when Typ.Procname.is_objc_block cl.name -> @@ -78,21 +78,20 @@ let resolve_method_with_block_args_and_analyze ~caller_summary pname act_params Typ.Procname.with_block_parameters pname block_name_args in (* new procdesc cloned from the original one, where the block parameters have been - replaced by the block arguments. The formals have also been expanded with the captured variables *) + replaced by the block arguments. The formals have also been expanded with the captured variables *) let specialized_pdesc = SpecializeProcdesc.with_block_args pdesc pname_with_block_args block_args in Logging.(debug Analysis Verbose) "Instructions of specialized method:@." ; Procdesc.iter_instrs (fun _ instr -> - Logging.(debug Analysis Verbose) "%a@." (Sil.pp_instr ~print_types:false Pp.text) instr - ) + Logging.(debug Analysis Verbose) "%a@." (Sil.pp_instr ~print_types:false Pp.text) instr ) specialized_pdesc ; Logging.(debug Analysis Verbose) "End of instructions@." ; match Ondemand.analyze_proc_desc ~caller_summary specialized_pdesc with | Some summary -> (* Since the closures in the formals were replaced by the captured variables, - we do the same with the actual arguments *) + we do the same with the actual arguments *) let extended_args = get_extended_args_for_method_with_block_analysis act_params in Some (summary, extended_args) | None -> diff --git a/infer/src/biabduction/Tabulation.ml b/infer/src/biabduction/Tabulation.ml index 984f20de1..8567a184d 100644 --- a/infer/src/biabduction/Tabulation.ml +++ b/infer/src/biabduction/Tabulation.ml @@ -426,14 +426,12 @@ let check_dereferences caller_pname tenv callee_pname actual_pre sub spec_pre fo None | deref_err :: _ -> ( (* Prefer to report Deref_null over other kinds of deref errors. this - * makes sure we report a NULL_DEREFERENCE instead of - a less interesting PRECONDITION_NOT_MET - * whenever possible *) + * makes sure we report a NULL_DEREFERENCE instead of + a less interesting PRECONDITION_NOT_MET + * whenever possible *) (* TOOD (t4893533): use this trick outside of angelic mode and in other parts of the code *) match - List.find - ~f:(fun err -> match err with Deref_null _, _ -> true | _ -> false) - deref_err_list + List.find ~f:(fun err -> match err with Deref_null _, _ -> true | _ -> false) deref_err_list with | Some x -> Some x @@ -664,11 +662,7 @@ let hpred_typing_lhs_compare hpred1 (e2, _) = let hpred_star_typing (hpred1 : Sil.hpred) (_, te2) : Sil.hpred = - match hpred1 with - | Sil.Hpointsto (e1, se1, _) -> - Sil.Hpointsto (e1, se1, te2) - | _ -> - assert false + match hpred1 with Sil.Hpointsto (e1, se1, _) -> Sil.Hpointsto (e1, se1, te2) | _ -> assert false (** Implementation of [*] between predicates and typings *) @@ -1013,9 +1007,9 @@ let mk_actual_precondition tenv prop actual_params formal_params = let mk_posts tenv prop callee_pname posts = let mk_getter_idempotent posts = (* if we have seen a previous call to the same function, only use specs whose return value - is consistent with constraints on the return value of the previous call w.r.t to - nullness. meant to eliminate false NPE warnings from the common - "if (get() != null) get().something()" pattern *) + is consistent with constraints on the return value of the previous call w.r.t to + nullness. meant to eliminate false NPE warnings from the common + "if (get() != null) get().something()" pattern *) let last_call_ret_non_null = List.exists ~f:(function @@ -1204,9 +1198,7 @@ let exe_spec exe_env tenv ret_id (n, nspecs) caller_pdesc callee_pname loc prop frame_typ missing_typ in let report_valid_res split = - match - combine tenv ret_id posts actual_pre path_pre split caller_pdesc callee_pname loc - with + match combine tenv ret_id posts actual_pre path_pre split caller_pdesc callee_pname loc with | None -> Invalid_res Cannot_combine | Some results -> @@ -1454,8 +1446,8 @@ let exe_call_postprocess tenv ret_id trace_call callee_pname callee_attrs loc re (** Execute the function call and return the list of results with return value *) -let exe_function_call ?dynamic_dispatch exe_env callee_summary tenv ret_id caller_pdesc - callee_pname loc actual_params prop path = +let exe_function_call ?dynamic_dispatch exe_env callee_summary tenv ret_id caller_pdesc callee_pname + loc actual_params prop path = let callee_attributes = Summary.get_attributes callee_summary in let caller_name = Procdesc.get_proc_name caller_pdesc in let trace_call = diff --git a/infer/src/bufferoverrun/absLoc.ml b/infer/src/bufferoverrun/absLoc.ml index 4a45526b4..e985117d5 100644 --- a/infer/src/bufferoverrun/absLoc.ml +++ b/infer/src/bufferoverrun/absLoc.ml @@ -133,46 +133,46 @@ module Loc = struct include (* Enforce invariants on Field and StarField, see Symb.mli *) ( struct - type t = - | Var of Var.t - | Allocsite of Allocsite.t - | Field of {prefix: t; fn: Typ.Fieldname.t; typ: field_typ} - | StarField of {prefix: t; last_field: Typ.Fieldname.t} - [@@deriving compare] - - let of_var v = Var v - - let of_allocsite a = Allocsite a - - let append_field ?typ l0 ~fn = - let rec aux = function - | Var _ | Allocsite _ -> - Field {prefix= l0; fn; typ} - | StarField {last_field} as l when Typ.Fieldname.equal fn last_field -> - l - | StarField {prefix} -> - StarField {prefix; last_field= fn} - | Field {fn= fn'} when Typ.Fieldname.equal fn fn' -> - StarField {prefix= l0; last_field= fn} - | Field {prefix= l} -> - aux l - in - aux l0 - - - let append_star_field l0 ~fn = - let rec aux = function - | Var _ | Allocsite _ -> - StarField {prefix= l0; last_field= fn} - | StarField {last_field} as l when Typ.Fieldname.equal fn last_field -> - l - | StarField {prefix} -> - StarField {prefix; last_field= fn} - | Field {prefix= l} -> - aux l - in - aux l0 - end : + type t = + | Var of Var.t + | Allocsite of Allocsite.t + | Field of {prefix: t; fn: Typ.Fieldname.t; typ: field_typ} + | StarField of {prefix: t; last_field: Typ.Fieldname.t} + [@@deriving compare] + + let of_var v = Var v + + let of_allocsite a = Allocsite a + + let append_field ?typ l0 ~fn = + let rec aux = function + | Var _ | Allocsite _ -> + Field {prefix= l0; fn; typ} + | StarField {last_field} as l when Typ.Fieldname.equal fn last_field -> + l + | StarField {prefix} -> + StarField {prefix; last_field= fn} + | Field {fn= fn'} when Typ.Fieldname.equal fn fn' -> + StarField {prefix= l0; last_field= fn} + | Field {prefix= l} -> + aux l + in + aux l0 + + + let append_star_field l0 ~fn = + let rec aux = function + | Var _ | Allocsite _ -> + StarField {prefix= l0; last_field= fn} + | StarField {last_field} as l when Typ.Fieldname.equal fn last_field -> + l + | StarField {prefix} -> + StarField {prefix; last_field= fn} + | Field {prefix= l} -> + aux l + in + aux l0 + end : sig type t = private | Var of Var.t diff --git a/infer/src/bufferoverrun/bounds.ml b/infer/src/bufferoverrun/bounds.ml index cf362ce1b..134d8a548 100644 --- a/infer/src/bufferoverrun/bounds.ml +++ b/infer/src/bufferoverrun/bounds.ml @@ -70,19 +70,18 @@ module SymLinear = struct M.for_all2 ~f:le_one_pair x y - let pp1 : - markup:bool -> is_beginning:bool -> F.formatter -> Symb.Symbol.t -> NonZeroInt.t -> unit = + let pp1 : markup:bool -> is_beginning:bool -> F.formatter -> Symb.Symbol.t -> NonZeroInt.t -> unit + = fun ~markup ~is_beginning f s c -> let c = (c :> Z.t) in let c = if is_beginning then c - else if Z.gt c Z.zero then ( F.pp_print_string f " + " ; c ) - else ( F.pp_print_string f " - " ; Z.neg c ) + else if Z.gt c Z.zero then (F.pp_print_string f " + " ; c) + else (F.pp_print_string f " - " ; Z.neg c) in if Z.(equal c one) then (Symb.Symbol.pp_mark ~markup) f s else if Z.(equal c minus_one) then F.fprintf f "-%a" (Symb.Symbol.pp_mark ~markup) s - else - F.fprintf f "%a%s%a" Z.pp_print c SpecialChars.dot_operator (Symb.Symbol.pp_mark ~markup) s + else F.fprintf f "%a%s%a" Z.pp_print c SpecialChars.dot_operator (Symb.Symbol.pp_mark ~markup) s let pp : markup:bool -> is_beginning:bool -> F.formatter -> t -> unit = @@ -578,11 +577,9 @@ module Bound = struct mk_MinMax (c2, Plus, Min, Z.(c1 - c2), SymLinear.get_one_symbol x2) | Linear (c1, x1), Linear (c2, x2) when SymLinear.is_one_symbol x1 && SymLinear.is_zero x2 -> mk_MinMax (c1, Plus, Min, Z.(c2 - c1), SymLinear.get_one_symbol x1) - | Linear (c1, x1), Linear (c2, x2) when SymLinear.is_zero x1 && SymLinear.is_mone_symbol x2 - -> + | Linear (c1, x1), Linear (c2, x2) when SymLinear.is_zero x1 && SymLinear.is_mone_symbol x2 -> mk_MinMax (c2, Minus, Max, Z.(c2 - c1), SymLinear.get_mone_symbol x2) - | Linear (c1, x1), Linear (c2, x2) when SymLinear.is_mone_symbol x1 && SymLinear.is_zero x2 - -> + | Linear (c1, x1), Linear (c2, x2) when SymLinear.is_mone_symbol x1 && SymLinear.is_zero x2 -> mk_MinMax (c1, Minus, Max, Z.(c1 - c2), SymLinear.get_mone_symbol x1) | MinMax (c1, (Plus as sign), (Min as minmax), _, s), Linear (c2, se) | Linear (c2, se), MinMax (c1, (Plus as sign), (Min as minmax), _, s) diff --git a/infer/src/bufferoverrun/bufferOverrunAnalysis.ml b/infer/src/bufferoverrun/bufferOverrunAnalysis.ml index 4887b5b6a..cdd137e8a 100644 --- a/infer/src/bufferoverrun/bufferOverrunAnalysis.ml +++ b/infer/src/bufferoverrun/bufferOverrunAnalysis.ml @@ -221,8 +221,8 @@ module TransferFunctions = struct let exec_instr : Dom.Mem.t -> extras ProcData.t -> CFG.Node.t -> Sil.instr -> Dom.Mem.t = - fun mem {summary; tenv; extras= {get_proc_summary_and_formals; oenv= {integer_type_widths}}} - node instr -> + fun mem {summary; tenv; extras= {get_proc_summary_and_formals; oenv= {integer_type_widths}}} node + instr -> match instr with | Load {id} when Ident.is_none id -> mem diff --git a/infer/src/bufferoverrun/bufferOverrunChecker.ml b/infer/src/bufferoverrun/bufferOverrunChecker.ml index c9c1ff180..dde20617a 100644 --- a/infer/src/bufferoverrun/bufferOverrunChecker.ml +++ b/infer/src/bufferoverrun/bufferOverrunChecker.ml @@ -33,8 +33,8 @@ module UnusedBranch = struct let desc = let err_desc = let i = match condition with Exp.Const (Const.Cint i) -> i | _ -> IntLit.zero in - Errdesc.explain_condition_always_true_false tenv i condition - (CFG.Node.underlying_node node) location + Errdesc.explain_condition_always_true_false tenv i condition (CFG.Node.underlying_node node) + location in F.asprintf "%a" Localise.pp_error_desc err_desc in @@ -88,7 +88,7 @@ module ExitStatement = struct (* check that we are the last significant instruction * of a procedure (no more significant instruction) * or of a block (goes directly to a node with multiple predecessors) - *) + *) let rec is_end_of_block_or_procedure (cfg : CFG.t) node rem_instrs = Instrs.for_all rem_instrs ~f:Sil.instr_is_auxiliary && @@ -192,8 +192,8 @@ let check_expr_for_array_access : let idx, idx_sym_exp = (Dom.Val.Itv.zero, Some Relation.SymExp.zero) in let relation = Dom.Mem.get_relation mem in let latest_prune = Dom.Mem.get_latest_prune mem in - BoUtils.Check.array_access ~arr ~idx ~idx_sym_exp ~relation ~is_plus:true - ~last_included:false ~latest_prune location cond_set + BoUtils.Check.array_access ~arr ~idx ~idx_sym_exp ~relation ~is_plus:true ~last_included:false + ~latest_prune location cond_set | Exp.BinOp (bop, e1, e2) -> check_binop integer_type_widths ~bop ~e1 ~e2 location mem cond_set | _ -> @@ -202,8 +202,7 @@ let check_expr_for_array_access : let check_binop_for_integer_overflow integer_type_widths bop ~lhs ~rhs location mem cond_set = match bop with - | Binop.MinusA (Some typ) when Typ.ikind_is_unsigned typ && Exp.is_zero lhs && Exp.is_const rhs - -> + | Binop.MinusA (Some typ) when Typ.ikind_is_unsigned typ && Exp.is_zero lhs && Exp.is_const rhs -> cond_set | Binop.PlusA (Some _) | Binop.MinusA (Some _) | Binop.Mult (Some _) -> let lhs_v = Sem.eval integer_type_widths lhs mem in @@ -258,9 +257,7 @@ let instantiate_cond : ) in let caller_rel = Dom.Mem.get_relation caller_mem in - let eval_sym_trace = - Sem.mk_eval_sym_trace integer_type_widths callee_formals params caller_mem - in + let eval_sym_trace = Sem.mk_eval_sym_trace integer_type_widths callee_formals params caller_mem in let latest_prune = Dom.Mem.get_latest_prune caller_mem in PO.ConditionSet.subst callee_cond eval_sym_trace rel_subst_map caller_rel callee_pname location latest_prune @@ -269,8 +266,7 @@ let instantiate_cond : type checks_summary = BufferOverrunCheckerSummary.t type get_proc_summary = - Typ.Procname.t - -> (BufferOverrunAnalysisSummary.t * (Pvar.t * Typ.t) list * checks_summary) option + Typ.Procname.t -> (BufferOverrunAnalysisSummary.t * (Pvar.t * Typ.t) list * checks_summary) option let check_instr : get_proc_summary @@ -348,8 +344,7 @@ let check_instrs : | {AbstractInterpreter.State.pre= Bottom | ExcRaised} -> checks | {AbstractInterpreter.State.pre= NonBottom _ as pre; post} -> - if Instrs.nth_exists instrs 1 then - L.(die InternalError) "Did not expect several instructions" ; + if Instrs.nth_exists instrs 1 then L.(die InternalError) "Did not expect several instructions" ; let instr = Instrs.nth_exn instrs 0 in let checks = match post with diff --git a/infer/src/bufferoverrun/bufferOverrunDomain.ml b/infer/src/bufferoverrun/bufferOverrunDomain.ml index cc1c78dfc..e4a476c1f 100644 --- a/infer/src/bufferoverrun/bufferOverrunDomain.ml +++ b/infer/src/bufferoverrun/bufferOverrunDomain.ml @@ -840,30 +840,30 @@ module AliasTarget = struct (* Relations between values of logical variables(registers) and program variables - "Simple relation": Since Sil distinguishes logical and program variables, we need a relation for + "Simple relation": Since Sil distinguishes logical and program variables, we need a relation for pruning values of program variables. For example, a C statement [if(x){...}] is translated to [%r=load(x); if(%r){...}] in Sil. At the load statement, we record the alias between the values of [%r] and [x], then we can prune not only the value of [%r], but also that of [x] inside the if branch. The [java_tmp] field is an additional slot for keeping one more alias of temporary variable in Java. The [i] field is to express [%r=load(x)+i]. - "Empty relation": For pruning [vector.length] with [vector::empty()] results, we adopt a specific + "Empty relation": For pruning [vector.length] with [vector::empty()] results, we adopt a specific relation between [%r] and [v->elements], where [%r=v.empty()]. So, if [%r!=0], [v]'s array length ([v->elements->length]) is pruned by [=0]. On the other hand, if [%r==0], [v]'s array length is pruned by [>=1]. - "Size relation": This is for pruning vector's length. When there is a function call, + "Size relation": This is for pruning vector's length. When there is a function call, [%r=x.size()], the alias target for [%r] becomes [AliasTarget.size {l=x.elements}]. The [java_tmp] field is an additional slot for keeping one more alias of temporary variable in Java. The [i] field is to express [%r=x.size()+i], which is required to follow the semantics of [Array.add] inside loops precisely. - "Iterator offset relation": This is for tracking a relation between an iterator offset and a + "Iterator offset relation": This is for tracking a relation between an iterator offset and a length of array. If [%r] has an alias to [IteratorOffset {l; i}], which means that [%r's iterator offset] is same to [length(l)+i]. - "HasNext relation": This is for tracking return values of the [hasNext] function. If [%r] has an - alias to [HasNext {l}], which means that [%r] is a [hasNext] results of the iterator [l]. *) + "HasNext relation": This is for tracking return values of the [hasNext] function. If [%r] has an + alias to [HasNext {l}], which means that [%r] is a [hasNext] results of the iterator [l]. *) type t = | Simple of {i: IntLit.t; java_tmp: Loc.t option} | Empty @@ -893,8 +893,8 @@ module AliasTarget = struct | Empty -> F.fprintf fmt "%t=empty(%t)" pp_lhs pp_rhs | Size {alias_typ; i; java_tmp} -> - F.fprintf fmt "%t%a%asize(%t)%a" pp_lhs pp_java_tmp java_tmp alias_typ_pp alias_typ - pp_rhs pp_intlit i + F.fprintf fmt "%t%a%asize(%t)%a" pp_lhs pp_java_tmp java_tmp alias_typ_pp alias_typ pp_rhs + pp_intlit i | Fgets -> F.fprintf fmt "%t=fgets(%t)" pp_lhs pp_rhs | IteratorOffset {alias_typ; i; java_tmp} -> @@ -1075,9 +1075,7 @@ module AliasTargets = struct let incr_size_alias loc x = update loc (Option.map ~f:AliasTarget.incr_size_alias) x - let incr_or_not_size_alias loc x = - update loc (Option.map ~f:AliasTarget.incr_or_not_size_alias) x - + let incr_or_not_size_alias loc x = update loc (Option.map ~f:AliasTarget.incr_or_not_size_alias) x let subst ~subst_loc x = let accum_substed rhs tgt acc = @@ -1935,9 +1933,7 @@ module MemReach = struct let add_heap : ?represents_multiple_values:bool -> Loc.t -> Val.t -> t -> t = fun ?represents_multiple_values x v m -> let v = - let sym = - if Itv.is_bottom (Val.get_itv v) then Relation.Sym.bot else Relation.Sym.of_loc x - in + let sym = if Itv.is_bottom (Val.get_itv v) then Relation.Sym.bot else Relation.Sym.of_loc x in let offset_sym, size_sym = if ArrayBlk.is_bot (Val.get_array_blk v) then (Relation.Sym.bot, Relation.Sym.bot) else (Relation.Sym.of_loc_offset x, Relation.Sym.of_loc_size x) @@ -2351,8 +2347,7 @@ module Mem = struct let add_heap : ?represents_multiple_values:bool -> Loc.t -> Val.t -> t -> t = - fun ?represents_multiple_values k v -> - map ~f:(MemReach.add_heap ?represents_multiple_values k v) + fun ?represents_multiple_values k v -> map ~f:(MemReach.add_heap ?represents_multiple_values k v) let add_heap_set : ?represents_multiple_values:bool -> PowLoc.t -> Val.t -> t -> t = diff --git a/infer/src/bufferoverrun/bufferOverrunDomainRelation.ml b/infer/src/bufferoverrun/bufferOverrunDomainRelation.ml index 6ead94fb0..3e3bd2c87 100644 --- a/infer/src/bufferoverrun/bufferOverrunDomainRelation.ml +++ b/infer/src/bufferoverrun/bufferOverrunDomainRelation.ml @@ -489,9 +489,7 @@ module Make (Manager : Manager_S) = struct a - let of_powloc var_of_loc locs = - PowLoc.fold (fun loc acc -> add (var_of_loc loc) acc) locs empty - + let of_powloc var_of_loc locs = PowLoc.fold (fun loc acc -> add (var_of_loc loc) acc) locs empty let int_of_powloc locs = of_powloc Var.of_loc locs @@ -1565,12 +1563,8 @@ module Make (Manager : Manager_S) = struct let init_array : - Allocsite.t - -> offset_opt:Itv.t option - -> size:Itv.t - -> size_exp_opt:SymExp.t option - -> t - -> t = + Allocsite.t -> offset_opt:Itv.t option -> size:Itv.t -> size_exp_opt:SymExp.t option -> t -> t + = fun allocsite ~offset_opt ~size ~size_exp_opt -> lift_default ~default:Bottom (PackedVal.init_array allocsite ~offset_opt ~size ~size_exp_opt) diff --git a/infer/src/bufferoverrun/bufferOverrunField.ml b/infer/src/bufferoverrun/bufferOverrunField.ml index 2046bbc2c..0bbf6b452 100644 --- a/infer/src/bufferoverrun/bufferOverrunField.ml +++ b/infer/src/bufferoverrun/bufferOverrunField.ml @@ -73,5 +73,4 @@ let cpp_vector_elem ~vec_typ ~elt_typ = mk ~cpp_classname:classname cpp_vector_elem_str {Typ.desc; quals= Typ.mk_type_quals ()} -let is_cpp_vector_elem fn = - String.equal (Typ.Fieldname.to_simplified_string fn) cpp_vector_elem_str +let is_cpp_vector_elem fn = String.equal (Typ.Fieldname.to_simplified_string fn) cpp_vector_elem_str diff --git a/infer/src/bufferoverrun/bufferOverrunModels.ml b/infer/src/bufferoverrun/bufferOverrunModels.ml index cfbe8da3e..ad8af075e 100644 --- a/infer/src/bufferoverrun/bufferOverrunModels.ml +++ b/infer/src/bufferoverrun/bufferOverrunModels.ml @@ -41,8 +41,8 @@ let at ?(size = Int64.zero) array_exp index_exp = (Sem.eval_lindex integer_type_widths array_exp index_exp mem) mem and check {location; integer_type_widths} mem cond_set = - BoUtils.Check.lindex integer_type_widths ~array_exp ~index_exp ~last_included:false mem - location cond_set + BoUtils.Check.lindex integer_type_widths ~array_exp ~index_exp ~last_included:false mem location + cond_set in {exec; check} @@ -67,8 +67,7 @@ let get_malloc_info : Exp.t -> Typ.t * Int.t option * Exp.t * Exp.t option = fun | Exp.BinOp (Binop.Mult _, length, Exp.Sizeof {typ; nbytes}) -> (typ, nbytes, length, None) (* In Java all arrays are dynamically allocated *) - | Exp.Sizeof {typ; nbytes; dynamic_length= Some arr_length} when Language.curr_language_is Java - -> + | Exp.Sizeof {typ; nbytes; dynamic_length= Some arr_length} when Language.curr_language_is Java -> (typ, nbytes, arr_length, Some arr_length) | Exp.Sizeof {typ; nbytes; dynamic_length} -> (typ, nbytes, Exp.one, dynamic_length) @@ -99,8 +98,7 @@ let fgets str_exp num_exp = let num = Dom.Val.get_itv num_v in Itv.plus offset (Itv.set_lb_zero (Itv.decr num)) in - Dom.Mem.set_first_idx_of_null (Loc.of_allocsite allocsite) (Dom.Val.of_itv ~traces strlen) - acc + Dom.Mem.set_first_idx_of_null (Loc.of_allocsite allocsite) (Dom.Val.of_itv ~traces strlen) acc in mem |> Dom.Mem.update_mem (Sem.eval_locs str_exp mem) Dom.Val.Itv.zero_255 @@ -115,8 +113,7 @@ let fgets str_exp num_exp = let malloc ~can_be_zero size_exp = - let exec ({pname; node_hash; location; tenv; integer_type_widths} as model_env) ~ret:(id, _) mem - = + let exec ({pname; node_hash; location; tenv; integer_type_widths} as model_env) ~ret:(id, _) mem = let size_exp = Prop.exp_normalize_noabs tenv Sil.sub_empty size_exp in let typ, stride, length0, dyn_length = get_malloc_info size_exp in let length = Sem.eval integer_type_widths length0 mem in @@ -276,9 +273,7 @@ let realloc src_exp size_exp = let size_exp = Prop.exp_normalize_noabs tenv Sil.sub_empty size_exp in let typ, _, length0, dyn_length = get_malloc_info size_exp in let length = Sem.eval integer_type_widths length0 mem in - let v = - Sem.eval integer_type_widths src_exp mem |> Dom.Val.set_array_length location ~length - in + let v = Sem.eval integer_type_widths src_exp mem |> Dom.Val.set_array_length location ~length in let mem = Dom.Mem.add_stack (Loc.of_id id) v mem in Option.value_map dyn_length ~default:mem ~f:(fun dyn_length -> let dyn_length = Dom.Val.get_itv (Sem.eval integer_type_widths dyn_length mem) in @@ -419,8 +414,7 @@ let set_array_length array length_exp = let size = Dom.Val.get_itv length in let allocsite = let represents_multiple_values = not (Itv.is_one size) in - Allocsite.make pname ~node_hash ~inst_num:0 ~dimension:1 ~path - ~represents_multiple_values + Allocsite.make pname ~node_hash ~inst_num:0 ~dimension:1 ~path ~represents_multiple_values in let v = Dom.Val.of_c_array_alloc allocsite ~stride ~offset:Itv.zero ~size ~traces in Dom.Mem.add_stack (Loc.of_pvar array_pvar) v mem @@ -665,8 +659,7 @@ module StdVector = struct let set_size {location} locs new_size mem = - Dom.Mem.transform_mem locs mem ~f:(fun v -> - Dom.Val.set_array_length location ~length:new_size v ) + Dom.Mem.transform_mem locs mem ~f:(fun v -> Dom.Val.set_array_length location ~length:new_size v) let empty elt_typ vec_arg = @@ -743,8 +736,8 @@ module StdBasicString = struct Option.value_map len_opt ~default:cond_set ~f:(fun len -> let {check= malloc_check} = malloc ~can_be_zero:true len in let cond_set = malloc_check model_env mem cond_set in - BoUtils.Check.lindex integer_type_widths ~array_exp:src ~index_exp:len - ~last_included:true mem location cond_set ) + BoUtils.Check.lindex integer_type_widths ~array_exp:src ~index_exp:len ~last_included:true + mem location cond_set ) in {exec; check} @@ -1351,8 +1344,7 @@ module Call = struct ; +PatternMatch.implements_collection &:: "" <>$ any_arg $+ capt_exp $--> Collection.init_with_capacity (* model sets as lists *) - ; +PatternMatch.implements_collections - &::+ unmodifiable <>$ capt_exp $--> Collection.iterator + ; +PatternMatch.implements_collections &::+ unmodifiable <>$ capt_exp $--> Collection.iterator ; +PatternMatch.implements_collections &:: "singleton" <>--> Collection.singleton_collection ; +PatternMatch.implements_collections &:: "emptySet" <>--> Collection.new_collection (* model maps as lists *) @@ -1413,8 +1405,7 @@ module Call = struct ; +PatternMatch.implements_nio "ByteBuffer" &:: "getShort" <>$ capt_exp $--> ByteBuffer.get_int ; +PatternMatch.implements_nio "ByteBuffer" &:: "getInt" <>$ capt_exp $--> ByteBuffer.get_int - ; +PatternMatch.implements_nio "ByteBuffer" - &:: "getLong" <>$ capt_exp $--> ByteBuffer.get_int + ; +PatternMatch.implements_nio "ByteBuffer" &:: "getLong" <>$ capt_exp $--> ByteBuffer.get_int ; -"java.lang.Object" &:: "clone" <>$ capt_exp $--> Object.clone ; +PatternMatch.implements_lang "Math" &:: "max" <>$ capt_exp $+ capt_exp diff --git a/infer/src/bufferoverrun/bufferOverrunProofObligations.ml b/infer/src/bufferoverrun/bufferOverrunProofObligations.ml index 8951ec2b4..bb3fcd561 100644 --- a/infer/src/bufferoverrun/bufferOverrunProofObligations.ml +++ b/infer/src/bufferoverrun/bufferOverrunProofObligations.ml @@ -78,9 +78,7 @@ module ConditionTrace = struct let check ~issue_type_u5 ~issue_type_r2 : _ t0 -> IssueType.t option = fun ct -> - if has_risky ct then Some issue_type_r2 - else if has_unknown ct then Some issue_type_u5 - else None + if has_risky ct then Some issue_type_r2 else if has_unknown ct then Some issue_type_u5 else None let check_buffer_overrun ct = @@ -178,8 +176,8 @@ module AllocSizeCondition = struct | cmp_big -> let propagate = match (cmp_mone, cmp_big) with - | (`NotComparable | `LeftSubsumesRight), _ - | _, (`NotComparable | `LeftSubsumesRight) -> + | (`NotComparable | `LeftSubsumesRight), _ | _, (`NotComparable | `LeftSubsumesRight) + -> is_symbolic | _ -> false @@ -337,22 +335,22 @@ module ArrayAccessCondition = struct (* basically, alarms involving infinity are filtered *) ((not (ItvPure.is_finite real_idx)) || not (ItvPure.is_finite c.size)) && (* except the following cases *) - not - ( Bound.is_not_infty (ItvPure.lb real_idx) - && (* idx non-infty lb < 0 *) - Bound.lt (ItvPure.lb real_idx) Bound.zero - || Bound.is_not_infty (ItvPure.lb real_idx) - && (* idx non-infty lb > size lb *) - Bound.gt (ItvPure.lb real_idx) (ItvPure.lb c.size) - || Bound.is_not_infty (ItvPure.lb real_idx) - && (* idx non-infty lb > size ub *) - Bound.gt (ItvPure.lb real_idx) (ItvPure.ub c.size) - || Bound.is_not_infty (ItvPure.ub real_idx) - && (* idx non-infty ub > size lb *) - Bound.gt (ItvPure.ub real_idx) (ItvPure.lb c.size) - || Bound.is_not_infty (ItvPure.ub real_idx) - && (* idx non-infty ub > size ub *) - Bound.gt (ItvPure.ub real_idx) (ItvPure.ub c.size) ) + not + ( Bound.is_not_infty (ItvPure.lb real_idx) + && (* idx non-infty lb < 0 *) + Bound.lt (ItvPure.lb real_idx) Bound.zero + || Bound.is_not_infty (ItvPure.lb real_idx) + && (* idx non-infty lb > size lb *) + Bound.gt (ItvPure.lb real_idx) (ItvPure.lb c.size) + || Bound.is_not_infty (ItvPure.lb real_idx) + && (* idx non-infty lb > size ub *) + Bound.gt (ItvPure.lb real_idx) (ItvPure.ub c.size) + || Bound.is_not_infty (ItvPure.ub real_idx) + && (* idx non-infty ub > size lb *) + Bound.gt (ItvPure.ub real_idx) (ItvPure.lb c.size) + || Bound.is_not_infty (ItvPure.ub real_idx) + && (* idx non-infty ub > size ub *) + Bound.gt (ItvPure.ub real_idx) (ItvPure.ub c.size) ) (* check buffer overrun and return its confidence *) @@ -735,14 +733,12 @@ module ConditionWithTrace = struct let pp fmt {cond; trace; reachability} = F.fprintf fmt "%a %a" Condition.pp cond ConditionTrace.pp trace ; - if Config.bo_debug >= 3 then - F.fprintf fmt " reachable when %a" Dom.Reachability.pp reachability + if Config.bo_debug >= 3 then F.fprintf fmt " reachable when %a" Dom.Reachability.pp reachability let pp_summary fmt {cond; trace; reachability} = F.fprintf fmt "%a %a" Condition.pp cond ConditionTrace.pp_summary trace ; - if Config.bo_debug >= 3 then - F.fprintf fmt " reachable when %a" Dom.Reachability.pp reachability + if Config.bo_debug >= 3 then F.fprintf fmt " reachable when %a" Dom.Reachability.pp reachability let have_same_bounds {cond= cond1} {cond= cond2} = Condition.equal cond1 cond2 @@ -818,7 +814,7 @@ module ConditionWithTrace = struct | Issue issue_type -> let issue_type = set_u5 cwt issue_type in (* Only report if the precision has improved. - This is approximated by: only report if the issue_type has changed. *) + This is approximated by: only report if the issue_type has changed. *) let report_issue_type = match cwt.reported with | Some reported when Reported.equal reported issue_type -> @@ -869,7 +865,7 @@ module ConditionSet = struct let try_merge ~existing:(existing_cwt, existing_checked) ~new_:(new_cwt, new_checked) = (* we don't want to remove issues that would end up in a higher bucket, - e.g. [a, b] < [c, d] is subsumed by [a, +oo] < [c, d] but the latter is less precise *) + e.g. [a, b] < [c, d] is subsumed by [a, +oo] < [c, d] but the latter is less precise *) let try_deduplicate () = match ConditionWithTrace.xcompare ~lhs:existing_cwt ~rhs:new_cwt with | `LeftSubsumesRight -> @@ -908,8 +904,8 @@ module ConditionSet = struct if same then condset else List.rev_append acc existings | `RemoveExistingAndContinue -> if Config.bo_debug >= 3 then - L.d_printfln_escaped "[InferboPO] Removing condition %a (because of new %a)@." - pp_cond existing pp_cond new_ ; + L.d_printfln_escaped "[InferboPO] Removing condition %a (because of new %a)@." pp_cond + existing pp_cond new_ ; aux acc ~same:false rest | `KeepExistingAndContinue -> aux (existing :: acc) ~same rest ) @@ -932,8 +928,7 @@ module ConditionSet = struct let add_array_access location ~offset ~idx ~size ~last_included ~idx_sym_exp ~size_sym_exp ~relation ~idx_traces ~arr_traces ~latest_prune condset = - ArrayAccessCondition.make ~offset ~idx ~size ~last_included ~idx_sym_exp ~size_sym_exp - ~relation + ArrayAccessCondition.make ~offset ~idx ~size ~last_included ~idx_sym_exp ~size_sym_exp ~relation |> Condition.make_array_access |> add_opt location (ValTrace.Issue.(binary location ArrayAccess) idx_traces arr_traces) @@ -955,12 +950,12 @@ module ConditionSet = struct latest_prune condset - let subst condset eval_sym_trace rel_subst_map caller_relation callee_pname call_site - latest_prune = + let subst condset eval_sym_trace rel_subst_map caller_relation callee_pname call_site latest_prune + = let subst_add_cwt condset cwt = match - ConditionWithTrace.subst eval_sym_trace rel_subst_map caller_relation callee_pname - call_site cwt + ConditionWithTrace.subst eval_sym_trace rel_subst_map caller_relation callee_pname call_site + cwt with | None -> condset diff --git a/infer/src/bufferoverrun/bufferOverrunSemantics.ml b/infer/src/bufferoverrun/bufferOverrunSemantics.ml index e5e8c9a1c..e93f93604 100644 --- a/infer/src/bufferoverrun/bufferOverrunSemantics.ml +++ b/infer/src/bufferoverrun/bufferOverrunSemantics.ml @@ -201,7 +201,7 @@ and eval_lindex integer_type_widths array_exp index_exp mem = memory sections for each array fields in struct, it finds the memory section using the abstract memory, though the memory lookup is not required to evaluate the address of - x.f[n] in the concrete semantics. *) + x.f[n] in the concrete semantics. *) let index_v = eval integer_type_widths index_exp mem in Val.plus_pi (Mem.find_set array_locs mem) index_v | _ -> @@ -219,13 +219,7 @@ and eval_lindex integer_type_widths array_exp index_exp mem = and eval_unop : Typ.IntegerWidths.t -> Unop.t -> Exp.t -> Mem.t -> Val.t = fun integer_type_widths unop e mem -> let v = eval integer_type_widths e mem in - match unop with - | Unop.Neg -> - Val.neg v - | Unop.BNot -> - Val.unknown_bit v - | Unop.LNot -> - Val.lnot v + match unop with Unop.Neg -> Val.neg v | Unop.BNot -> Val.unknown_bit v | Unop.LNot -> Val.lnot v and eval_binop : Typ.IntegerWidths.t -> Binop.t -> Exp.t -> Exp.t -> Mem.t -> Val.t = @@ -485,9 +479,7 @@ let mk_eval_sym_cost = mk_eval_sym_mode ~mode:EvalCost let get_sym_f integer_type_widths mem e = Val.get_sym (eval integer_type_widths e mem) -let get_offset_sym_f integer_type_widths mem e = - Val.get_offset_sym (eval integer_type_widths e mem) - +let get_offset_sym_f integer_type_widths mem e = Val.get_offset_sym (eval integer_type_widths e mem) let get_size_sym_f integer_type_widths mem e = Val.get_size_sym (eval integer_type_widths e mem) @@ -863,8 +855,8 @@ let get_matching_pairs : [] |> add_pair_val callee_v actual ~e2_opt:actual_exp_opt |> add_pair_ptr typ callee_v actual -let subst_map_of_rel_pairs : - (Relation.Var.t * Relation.SymExp.t option) list -> Relation.SubstMap.t = +let subst_map_of_rel_pairs : (Relation.Var.t * Relation.SymExp.t option) list -> Relation.SubstMap.t + = fun pairs -> let add_pair rel_map (x, e) = Relation.SubstMap.add x e rel_map in List.fold pairs ~init:Relation.SubstMap.empty ~f:add_pair diff --git a/infer/src/bufferoverrun/bufferOverrunTrace.ml b/infer/src/bufferoverrun/bufferOverrunTrace.ml index 461099158..81888b824 100644 --- a/infer/src/bufferoverrun/bufferOverrunTrace.ml +++ b/infer/src/bufferoverrun/bufferOverrunTrace.ml @@ -193,8 +193,7 @@ module BoTrace = struct | Call {location; caller; callee} -> let desc = "Call" in let tail = - Errlog.make_trace_element depth location desc [] - :: make_err_trace (depth + 1) callee tail + Errlog.make_trace_element depth location desc [] :: make_err_trace (depth + 1) callee tail in make_err_trace depth caller tail end @@ -242,7 +241,11 @@ end module Issue = struct type elem = Alloc [@@deriving compare] - type binary = ArrayAccess (* offset, length *) | Binop [@@deriving compare] + type binary = + | ArrayAccess + (* offset, length *) + | Binop + [@@deriving compare] type t = | Elem of {location: Location.t; length: int; kind: elem; from: Set.t} diff --git a/infer/src/bufferoverrun/bufferOverrunUtils.ml b/infer/src/bufferoverrun/bufferOverrunUtils.ml index 63495a510..e2dd1cce9 100644 --- a/infer/src/bufferoverrun/bufferOverrunUtils.ml +++ b/infer/src/bufferoverrun/bufferOverrunUtils.ml @@ -36,8 +36,7 @@ module Exec = struct let v = Dom.Mem.find_set ~typ locs mem in let mem = Dom.Mem.add_stack (Loc.of_id id) v mem in let mem = - if represents_multiple_values then - Dom.Mem.add_heap_set ~represents_multiple_values locs v mem + if represents_multiple_values then Dom.Mem.add_heap_set ~represents_multiple_values locs v mem else mem in match PowLoc.is_singleton_or_more locs with @@ -65,8 +64,8 @@ module Exec = struct (mem, inst_num) - and decl_local_array ({pname; node_hash; location} as model_env) loc typ ~length ?stride - ~inst_num ~represents_multiple_values ~dimension mem = + and decl_local_array ({pname; node_hash; location} as model_env) loc typ ~length ?stride ~inst_num + ~represents_multiple_values ~dimension mem = let size = Option.value_map ~default:Itv.top ~f:Itv.of_int_lit length in let path = Loc.get_path loc in let allocsite = @@ -156,9 +155,7 @@ module Exec = struct match field_typ.Typ.desc with | Tarray {length= Some length} -> let length = Itv.plus (Itv.of_int_lit length) dyn_length |> Dom.Val.of_itv in - let v = - Dom.Mem.find_set field_loc mem |> Dom.Val.set_array_length location ~length - in + let v = Dom.Mem.find_set field_loc mem |> Dom.Val.set_array_length location ~length in Dom.Mem.strong_update field_loc v mem | _ -> set_dyn_length model_env field_typ field_loc dyn_length mem ) diff --git a/infer/src/bufferoverrun/itv.ml b/infer/src/bufferoverrun/itv.ml index 6eceb8ec9..8beaa3937 100644 --- a/infer/src/bufferoverrun/itv.ml +++ b/infer/src/bufferoverrun/itv.ml @@ -431,11 +431,7 @@ module ItvPure = struct let prune_eq : t -> t -> t bottom_lifted = fun x y -> - match prune_comp Binop.Le x y with - | Bottom -> - Bottom - | NonBottom x' -> - prune_comp Binop.Ge x' y + match prune_comp Binop.Le x y with Bottom -> Bottom | NonBottom x' -> prune_comp Binop.Ge x' y let prune_eq_zero : t -> t bottom_lifted = diff --git a/infer/src/bufferoverrun/polynomials.ml b/infer/src/bufferoverrun/polynomials.ml index cca90a6a9..5952fc6a6 100644 --- a/infer/src/bufferoverrun/polynomials.ml +++ b/infer/src/bufferoverrun/polynomials.ml @@ -244,7 +244,7 @@ module MakePolynomial (S : NonNegativeSymbolWithDegreeKind) = struct (* (c + r * R + s * S + t * T) x s - = 0 + r * (R x s) + s * (c + s * S + t * T) *) + = 0 + r * (R x s) + s * (c + s * S + t * T) *) let rec mult_symb : t -> S.t -> t = fun {const; terms} s -> let less_than_s, equal_s_opt, greater_than_s = M.split s terms in @@ -296,8 +296,7 @@ module MakePolynomial (S : NonNegativeSymbolWithDegreeKind) = struct fun ~lhs ~rhs -> phys_equal lhs rhs || (NonNegativeInt.leq ~lhs:lhs.const ~rhs:rhs.const && M.le ~le_elt:leq lhs.terms rhs.terms) - || Option.exists (int_ub lhs) ~f:(fun lhs_ub -> - NonNegativeInt.leq ~lhs:lhs_ub ~rhs:(int_lb rhs) ) + || Option.exists (int_ub lhs) ~f:(fun lhs_ub -> NonNegativeInt.leq ~lhs:lhs_ub ~rhs:(int_lb rhs)) let rec xcompare ~lhs ~rhs = @@ -315,8 +314,7 @@ module MakePolynomial (S : NonNegativeSymbolWithDegreeKind) = struct (fun s p acc -> let p' = mask_min_max_constant p in M.update (S.mask_min_max_constant s) - (function - | None -> Some p' | Some p -> if leq ~lhs:p ~rhs:p' then Some p' else Some p ) + (function None -> Some p' | Some p -> if leq ~lhs:p ~rhs:p' then Some p' else Some p) acc ) terms M.empty } diff --git a/infer/src/bufferoverrun/symb.ml b/infer/src/bufferoverrun/symb.ml index ea03dea6c..43c60555d 100644 --- a/infer/src/bufferoverrun/symb.ml +++ b/infer/src/bufferoverrun/symb.ml @@ -19,11 +19,7 @@ module BoundEnd = struct end module SymbolPath = struct - type deref_kind = - | Deref_ArrayIndex - | Deref_COneValuePointer - | Deref_CPointer - | Deref_JavaPointer + type deref_kind = Deref_ArrayIndex | Deref_COneValuePointer | Deref_CPointer | Deref_JavaPointer let compare_deref_kind _ _ = 0 @@ -33,49 +29,49 @@ module SymbolPath = struct include (* Enforce invariants on Field and StarField *) ( struct - type partial = - | Pvar of Pvar.t - | Deref of deref_kind * partial - | Field of {fn: Typ.Fieldname.t; prefix: partial; typ: field_typ} - | Callsite of {ret_typ: Typ.t; cs: CallSite.t} - | StarField of {last_field: Typ.Fieldname.t; prefix: partial} - [@@deriving compare] - - let of_pvar pvar = Pvar pvar - - let of_callsite ~ret_typ cs = Callsite {ret_typ; cs} - - let deref ~deref_kind p = Deref (deref_kind, p) - - let star_field p0 fn = - let rec aux = function - | Pvar _ | Callsite _ -> - StarField {last_field= fn; prefix= p0} - | Deref (_, p) | Field {prefix= p} -> - aux p - | StarField {last_field} as p when Typ.Fieldname.equal fn last_field -> - p - | StarField {prefix} -> - StarField {last_field= fn; prefix} - in - aux p0 - - - let field ?typ p0 fn = - let rec aux = function - | Pvar _ | Callsite _ -> - Field {fn; prefix= p0; typ} - | Field {fn= fn'} when Typ.Fieldname.equal fn fn' -> - StarField {last_field= fn; prefix= p0} - | Field {prefix= p} | Deref (_, p) -> - aux p - | StarField {last_field} as p when Typ.Fieldname.equal fn last_field -> - p - | StarField {prefix} -> - StarField {last_field= fn; prefix} - in - aux p0 - end : + type partial = + | Pvar of Pvar.t + | Deref of deref_kind * partial + | Field of {fn: Typ.Fieldname.t; prefix: partial; typ: field_typ} + | Callsite of {ret_typ: Typ.t; cs: CallSite.t} + | StarField of {last_field: Typ.Fieldname.t; prefix: partial} + [@@deriving compare] + + let of_pvar pvar = Pvar pvar + + let of_callsite ~ret_typ cs = Callsite {ret_typ; cs} + + let deref ~deref_kind p = Deref (deref_kind, p) + + let star_field p0 fn = + let rec aux = function + | Pvar _ | Callsite _ -> + StarField {last_field= fn; prefix= p0} + | Deref (_, p) | Field {prefix= p} -> + aux p + | StarField {last_field} as p when Typ.Fieldname.equal fn last_field -> + p + | StarField {prefix} -> + StarField {last_field= fn; prefix} + in + aux p0 + + + let field ?typ p0 fn = + let rec aux = function + | Pvar _ | Callsite _ -> + Field {fn; prefix= p0; typ} + | Field {fn= fn'} when Typ.Fieldname.equal fn fn' -> + StarField {last_field= fn; prefix= p0} + | Field {prefix= p} | Deref (_, p) -> + aux p + | StarField {last_field} as p when Typ.Fieldname.equal fn last_field -> + p + | StarField {prefix} -> + StarField {last_field= fn; prefix} + in + aux p0 + end : sig type partial = private | Pvar of Pvar.t @@ -269,14 +265,11 @@ module Symbol = struct let compare_extra_bool _ _ = 0 (* NOTE: non_int represents the symbols that are not integer type, - so that their ranges are not used in the cost checker. *) + so that their ranges are not used in the cost checker. *) type t = | OneValue of {unsigned: extra_bool; non_int: extra_bool; path: SymbolPath.t} | BoundEnd of - { unsigned: extra_bool - ; non_int: extra_bool - ; path: SymbolPath.t - ; bound_end: BoundEnd.t } + {unsigned: extra_bool; non_int: extra_bool; path: SymbolPath.t; bound_end: BoundEnd.t} [@@deriving compare] let pp : F.formatter -> t -> unit = @@ -317,8 +310,8 @@ module Symbol = struct match (s1, s2) with | OneValue _, BoundEnd _ | BoundEnd _, OneValue _ -> false - | OneValue {path= path1}, OneValue {path= path2} - | BoundEnd {path= path1}, BoundEnd {path= path2} -> + | OneValue {path= path1}, OneValue {path= path2} | BoundEnd {path= path1}, BoundEnd {path= path2} + -> SymbolPath.equal path1 path2 diff --git a/infer/src/bufferoverrun/symb.mli b/infer/src/bufferoverrun/symb.mli index 57c835f11..4ed1aceaf 100644 --- a/infer/src/bufferoverrun/symb.mli +++ b/infer/src/bufferoverrun/symb.mli @@ -15,11 +15,7 @@ module BoundEnd : sig end module SymbolPath : sig - type deref_kind = - | Deref_ArrayIndex - | Deref_COneValuePointer - | Deref_CPointer - | Deref_JavaPointer + type deref_kind = Deref_ArrayIndex | Deref_COneValuePointer | Deref_CPointer | Deref_JavaPointer [@@deriving compare] type partial = private diff --git a/infer/src/checkers/LithoFramework.ml b/infer/src/checkers/LithoFramework.ml index 381515481..342007871 100644 --- a/infer/src/checkers/LithoFramework.ml +++ b/infer/src/checkers/LithoFramework.ml @@ -128,15 +128,14 @@ struct if ( LithoContext.check_callee ~callee_pname ~tenv callee_summary_opt || (* track callee in order to report respective errors *) - Domain.mem receiver astate - (* track anything called on a receiver we're already tracking *) ) + Domain.mem receiver astate + (* track anything called on a receiver we're already tracking *) ) && (not (Typ.Procname.Java.is_static java_callee_procname)) && LithoContext.satisfies_heuristic ~callee_pname ~callee_summary_opt tenv then let return_access_path = Domain.LocalAccessPath.make (return_base, []) caller_pname in let return_calls = - ( try Domain.find return_access_path astate - with Caml.Not_found -> Domain.CallSet.empty ) + (try Domain.find return_access_path astate with Caml.Not_found -> Domain.CallSet.empty) |> Domain.CallSet.add (Domain.MethodCall.make receiver callee_pname location) in Domain.add return_access_path return_calls astate diff --git a/infer/src/checkers/NullabilityPreanalysis.ml b/infer/src/checkers/NullabilityPreanalysis.ml index dd923b46c..f6a1f0959 100644 --- a/infer/src/checkers/NullabilityPreanalysis.ml +++ b/infer/src/checkers/NullabilityPreanalysis.ml @@ -49,7 +49,7 @@ module TransferFunctions (CFG : ProcCfg.S) = struct | Typ.Tptr ({desc= Tfun _}, _) when Typ.is_objc_class typ && is_self proc_data.extras lhs_id && (* lhs is self, rhs is not null *) - not (exp_is_null proc_data.extras rhs) -> + not (exp_is_null proc_data.extras rhs) -> FieldsAssignedInConstructors.add (name, typ) astate | _ -> astate ) diff --git a/infer/src/checkers/RequiredProps.ml b/infer/src/checkers/RequiredProps.ml index 7d2cbf929..cc247ff1a 100644 --- a/infer/src/checkers/RequiredProps.ml +++ b/infer/src/checkers/RequiredProps.ml @@ -19,12 +19,12 @@ let get_required_props typename tenv = ~f:(fun (({Annot.parameters} as annot), _) -> Annotations.annot_ends_with annot Annotations.prop && (* Don't count as required if it's @Prop(optional = true) *) - not - (List.exists - ~f:(fun Annot.{name; value} -> - Option.value_map name ~default:false ~f:(fun name -> String.equal "optional" name) - && String.equal value "true" ) - parameters) ) + not + (List.exists + ~f:(fun Annot.{name; value} -> + Option.value_map name ~default:false ~f:(fun name -> String.equal "optional" name) + && String.equal value "true" ) + parameters) ) annot_list in let get_var_args annot_list = @@ -32,7 +32,7 @@ let get_required_props typename tenv = ~f:(fun acc (({Annot.parameters} as annot), _) -> if Annotations.annot_ends_with annot Annotations.prop then (* Pick up the parameter for varArg if it has the form - @Prop(varArg = myProp). *) + @Prop(varArg = myProp). *) List.fold ~init:acc ~f:(fun acc Annot.{name; value} -> if Option.value_map name ~default:false ~f:(fun name -> String.equal "varArg" name) @@ -98,11 +98,11 @@ let has_prop prop_set prop = let check prop = String.Set.mem prop_set prop || (* @Prop(resType = ...) myProp can also be set via myProp(), myPropAttr(), myPropDip(), myPropPx(), myPropRes() or myPropSp(). - Our annotation parameter parsing is too primitive to identify resType, so just assume - that all @Prop's can be set any of these 6 ways. *) - String.Set.exists prop_set ~f:(fun el -> - String.chop_prefix el ~prefix:prop - |> Option.exists ~f:(fun suffix -> String.Set.mem suffixes suffix) ) + Our annotation parameter parsing is too primitive to identify resType, so just assume + that all @Prop's can be set any of these 6 ways. *) + String.Set.exists prop_set ~f:(fun el -> + String.chop_prefix el ~prefix:prop + |> Option.exists ~f:(fun suffix -> String.Set.mem suffixes suffix) ) in match prop with | Prop prop -> @@ -156,8 +156,8 @@ module LithoContext = struct | Domain.MethodCall.{procname} :: _ when LithoFramework.is_component_build_method procname tenv -> ( (* Here, we'll have a type name like MyComponent$Builder in hand. Truncate the $Builder - part from the typename, then look at the fields of MyComponent to figure out which - ones are annotated with @Prop *) + part from the typename, then look at the fields of MyComponent to figure out which + ones are annotated with @Prop *) match find_client_component_type call_chain with | Some parent_typename -> let required_props = get_required_props parent_typename tenv in diff --git a/infer/src/checkers/Siof.ml b/infer/src/checkers/Siof.ml index fd9816471..38b170f4c 100644 --- a/infer/src/checkers/Siof.ml +++ b/infer/src/checkers/Siof.ml @@ -88,7 +88,7 @@ module TransferFunctions (CFG : ProcCfg.S) = struct Domain.VarNames.elements initialized |> QualifiedCppName.Match.of_fuzzy_qual_names in Staged.stage (fun (* gvar \notin initialized, up to some fuzzing *) - gvar -> + gvar -> QualifiedCppName.of_qual_string (Pvar.to_string gvar) |> Fn.non (QualifiedCppName.Match.match_qualifiers initialized_matcher) ) @@ -198,11 +198,11 @@ module TransferFunctions (CFG : ProcCfg.S) = struct add_actuals_globals astate summary loc actuals |> Domain.join callee_astate |> (* make sure it's not Bottom: we made a function call so this needs initialization *) - at_least_nonbottom + at_least_nonbottom | Call (_, _, actuals, loc, _) -> add_actuals_globals astate summary loc actuals |> (* make sure it's not Bottom: we made a function call so this needs initialization *) - at_least_nonbottom + at_least_nonbottom | Metadata _ -> astate @@ -235,8 +235,8 @@ let report_siof summary trace gname loc = assert false | (final_sink, _) :: _ -> F.asprintf - "Initializer of %s accesses global variable from a different translation unit: %a" - gname GlobalVar.pp (SiofTrace.Sink.kind final_sink) + "Initializer of %s accesses global variable from a different translation unit: %a" gname + GlobalVar.pp (SiofTrace.Sink.kind final_sink) in let ltr = SiofTrace.trace_of_error loc gname trace in Reporting.log_error summary ~loc ~ltr IssueType.static_initialization_order_fiasco description diff --git a/infer/src/checkers/Trace.ml b/infer/src/checkers/Trace.ml index 2808d7d69..bb6712c72 100644 --- a/infer/src/checkers/Trace.ml +++ b/infer/src/checkers/Trace.ml @@ -53,10 +53,7 @@ module type S = sig type path = Passthroughs.t * (Source.t * Passthroughs.t) list * (Sink.t * Passthroughs.t) list type report = - { issue: IssueType.t - ; path_source: Source.t - ; path_sink: Sink.t - ; path_passthroughs: Passthroughs.t } + {issue: IssueType.t; path_source: Source.t; path_sink: Sink.t; path_passthroughs: Passthroughs.t} val sources : t -> Sources.t (** get the sources of the trace. *) @@ -126,9 +123,7 @@ module Expander (TraceElem : TraceElem.S) = struct let caller_elem_kind = TraceElem.kind elem in let seen_acc' = CallSite.Set.add caller_elem_site seen_acc in let elems, passthroughs = elems_passthroughs_of_pname (CallSite.pname caller_elem_site) in - let is_recursive callee_elem seen = - CallSite.Set.mem (TraceElem.call_site callee_elem) seen - in + let is_recursive callee_elem seen = CallSite.Set.mem (TraceElem.call_site callee_elem) seen in (* find sinks that are the same kind as the caller, but have a different procname *) let matching_elems = List.filter @@ -246,10 +241,7 @@ module Make (Spec : Spec) = struct type path = Passthroughs.t * (Source.t * Passthroughs.t) list * (Sink.t * Passthroughs.t) list type report = - { issue: IssueType.t - ; path_source: Source.t - ; path_sink: Sink.t - ; path_passthroughs: Passthroughs.t } + {issue: IssueType.t; path_source: Source.t; path_sink: Sink.t; path_passthroughs: Passthroughs.t} let pp fmt {sources; sinks; passthroughs} = let pp_passthroughs fmt passthroughs = @@ -401,9 +393,7 @@ module Make (Spec : Spec) = struct let trace_elems_of_passthroughs lt_level passthroughs acc0 = let trace_elem_of_passthrough passthrough acc = let passthrough_site = Passthrough.site passthrough in - let desc = - F.asprintf "flow through %a" Typ.Procname.pp (CallSite.pname passthrough_site) - in + let desc = F.asprintf "flow through %a" Typ.Procname.pp (CallSite.pname passthrough_site) in Errlog.make_trace_element lt_level (CallSite.loc passthrough_site) desc [] :: acc in (* sort passthroughs by ascending line number to create a coherent trace *) @@ -518,8 +508,7 @@ module Make (Spec : Spec) = struct let footprint_indices = Sources.Footprint.BaseMap.fold (fun (vname, _) _ s -> - match Var.get_footprint_index vname with Some ind -> IntSet.add ind s | None -> s - ) + match Var.get_footprint_index vname with Some ind -> IntSet.add ind s | None -> s ) callee_trace.sources.footprint IntSet.empty in List.map diff --git a/infer/src/checkers/Trace.mli b/infer/src/checkers/Trace.mli index 93db63521..d7e7f5f46 100644 --- a/infer/src/checkers/Trace.mli +++ b/infer/src/checkers/Trace.mli @@ -23,20 +23,20 @@ end module type S = sig include Spec - (** bottom = this trace has no source or sink data *) include AbstractDomain.WithBottom + (** bottom = this trace has no source or sink data *) module Sources : sig - (** Set of sources returned by callees of the current function *) module Known : module type of AbstractDomain.FiniteSet (Source) + (** Set of sources returned by callees of the current function *) module FootprintConfig : AccessTree.Config - (** Set of access paths representing the sources that may flow in from the caller *) module Footprint : module type of AccessTree.PathSet (FootprintConfig) + (** Set of access paths representing the sources that may flow in from the caller *) - (** Set of sanitizers that have been applied to these sources *) module Sanitizers : module type of AbstractDomain.FiniteSet (Sanitizer) + (** Set of sanitizers that have been applied to these sources *) type t = {known: Known.t; footprint: Footprint.t; sanitizers: Sanitizers.t} @@ -62,10 +62,7 @@ module type S = sig type path = Passthroughs.t * (Source.t * Passthroughs.t) list * (Sink.t * Passthroughs.t) list type report = - { issue: IssueType.t - ; path_source: Source.t - ; path_sink: Sink.t - ; path_passthroughs: Passthroughs.t } + {issue: IssueType.t; path_source: Source.t; path_sink: Sink.t; path_passthroughs: Passthroughs.t} val sources : t -> Sources.t (** get the sources of the trace. *) diff --git a/infer/src/checkers/accessTree.ml b/infer/src/checkers/accessTree.ml index cd433b468..55b955764 100644 --- a/infer/src/checkers/accessTree.ml +++ b/infer/src/checkers/accessTree.ml @@ -16,7 +16,8 @@ module type S = sig module BaseMap = AccessPath.BaseMap type node = TraceDomain.t * tree - and tree = Subtree of node AccessMap.t | Star + + and tree = Subtree of node AccessMap.t | Star include AbstractDomain.WithBottom with type t = node BaseMap.t @@ -295,9 +296,9 @@ module Make (TraceDomain : AbstractDomain.WithBottom) (Config : Config) = struct try AccessMap.find access subtree with Caml.Not_found -> empty_normal_leaf in (* once we encounter a subtree rooted in an array access, we have to do weak updates in - the entire subtree. the reason: if I do x[i].f.g = , then - x[j].f.g = , I don't want to overwrite . instead, I - should get |_| *) + the entire subtree. the reason: if I do x[i].f.g = , then + x[j].f.g = , I don't want to overwrite . instead, I + should get |_| *) let seen_array_access = seen_array_access || diff --git a/infer/src/checkers/annotationReachability.ml b/infer/src/checkers/annotationReachability.ml index acd32dd6b..0357127c4 100644 --- a/infer/src/checkers/annotationReachability.ml +++ b/infer/src/checkers/annotationReachability.ml @@ -52,8 +52,8 @@ let is_allocator tenv pname = let check_attributes check tenv pname = PatternMatch.check_class_attributes check tenv pname - || Annotations.pname_has_return_annot pname - ~attrs_of_pname:Summary.OnDisk.proc_resolve_attributes check + || Annotations.pname_has_return_annot pname ~attrs_of_pname:Summary.OnDisk.proc_resolve_attributes + check let method_overrides is_annotated tenv pname = @@ -94,12 +94,11 @@ let report_allocation_stack src_annot summary fst_call_loc trace stack_str const MF.pp_monospaced ("@" ^ src_annot) MF.pp_monospaced constr_str MF.pp_monospaced (stack_str ^ "new " ^ constr_str) in - Reporting.log_error summary ~loc:fst_call_loc ~ltr:final_trace - IssueType.checkers_allocates_memory description + Reporting.log_error summary ~loc:fst_call_loc ~ltr:final_trace IssueType.checkers_allocates_memory + description -let report_annotation_stack src_annot snk_annot src_summary loc trace stack_str snk_pname call_loc - = +let report_annotation_stack src_annot snk_annot src_summary loc trace stack_str snk_pname call_loc = let src_pname = Summary.get_proc_name src_summary in if String.equal snk_annot dummy_constructor_annot then report_allocation_stack src_annot src_summary loc trace stack_str snk_pname call_loc diff --git a/infer/src/checkers/annotations.ml b/infer/src/checkers/annotations.ml index 827eba69d..a66718773 100644 --- a/infer/src/checkers/annotations.ml +++ b/infer/src/checkers/annotations.ml @@ -215,9 +215,7 @@ let field_injector_readonly_list = inject :: field_injector_readwrite_list (** Annotations for readonly injectors. The injector framework initializes the field but does not write null into it. *) -let ia_is_field_injector_readonly ia = - List.exists ~f:(ia_ends_with ia) field_injector_readonly_list - +let ia_is_field_injector_readonly ia = List.exists ~f:(ia_ends_with ia) field_injector_readonly_list (** Annotations for read-write injectors. The injector framework initializes the field and can write null into it. *) diff --git a/infer/src/checkers/classLoads.ml b/infer/src/checkers/classLoads.ml index 6b24b5c10..062f828b9 100644 --- a/infer/src/checkers/classLoads.ml +++ b/infer/src/checkers/classLoads.ml @@ -100,7 +100,7 @@ let exec_instr summary tenv astate _ (instr : Sil.instr) = | Call (_, Const (Cfun callee), args, loc, _) -> exec_call summary tenv callee args loc astate | Load {e= exp; loc} | Prune (exp, loc, _, _) -> - (* NB the java frontend seems to always translate complex guards into a sequence of + (* NB the java frontend seems to always translate complex guards into a sequence of instructions plus a prune on logical vars only. So the below is only for completeness. *) add_loads_of_exp summary tenv loc exp astate | Store {e1; e2; loc} -> diff --git a/infer/src/checkers/control.ml b/infer/src/checkers/control.ml index 78aa52e36..75cc8cbf2 100644 --- a/infer/src/checkers/control.ml +++ b/infer/src/checkers/control.ml @@ -35,17 +35,17 @@ end module ControlDepSet = AbstractDomain.FiniteSet (CVar) -(** Map control var -> loop head location *) module ControlMap = PrettyPrintable.MakePPMap (Var) +(** Map control var -> loop head location *) module GuardNodes = AbstractDomain.FiniteSet (Procdesc.Node) module LoopHeads = Procdesc.NodeSet -(** Map exit node -> loop head set *) module ExitNodeToLoopHeads = Procdesc.NodeMap +(** Map exit node -> loop head set *) -(** Map loop head -> prune nodes in the loop guard *) module LoopHeadToGuardNodes = Procdesc.NodeMap +(** Map loop head -> prune nodes in the loop guard *) type loop_control_maps = { exit_map: LoopHeads.t ExitNodeToLoopHeads.t diff --git a/infer/src/checkers/control.mli b/infer/src/checkers/control.mli index 1213c2d18..fc68b36d9 100644 --- a/infer/src/checkers/control.mli +++ b/infer/src/checkers/control.mli @@ -9,16 +9,16 @@ open! IStd module LoopHead = Procdesc.Node module LoopHeads = Procdesc.NodeSet -(** Map control var -> loop head location *) module ControlMap : module type of PrettyPrintable.MakePPMap (Var) +(** Map control var -> loop head location *) module GuardNodes : module type of AbstractDomain.FiniteSet (Procdesc.Node) -(** Map exit node -> loop head set *) module ExitNodeToLoopHeads = Procdesc.NodeMap +(** Map exit node -> loop head set *) -(** Map loop head -> prune nodes in the loop guard *) module LoopHeadToGuardNodes = Procdesc.NodeMap +(** Map loop head -> prune nodes in the loop guard *) type invariant_map diff --git a/infer/src/checkers/cost.ml b/infer/src/checkers/cost.ml index 0995d9c23..4be1760c9 100644 --- a/infer/src/checkers/cost.ml +++ b/infer/src/checkers/cost.ml @@ -91,7 +91,7 @@ module BoundMap = struct ~node_id mem in (* The zero cost of node does not make sense especially when the abstract memory - is non-bottom. *) + is non-bottom. *) if BasicCost.is_zero cost then BasicCost.one else cost in L.(debug Analysis Medium) @@ -119,7 +119,7 @@ end module ControlFlowCost = struct (* A Control-flow cost represents the number of times the flow of control can go through a certain CFG item (a node or an edge), - or a sum of such things *) + or a sum of such things *) module Item = struct type t = [`Node of Node.id | `Edge of Node.id * Node.id] @@ -166,9 +166,7 @@ module ControlFlowCost = struct fun (`Sum (l1, s1)) (`Sum (l2, s2)) -> [%compare: int * Item.t list] (l1, s1) (l2, s2) - let pp : F.formatter -> t -> unit = - fun fmt (`Sum (_, set)) -> Pp.seq ~sep:" + " Item.pp fmt set - + let pp : F.formatter -> t -> unit = fun fmt (`Sum (_, set)) -> Pp.seq ~sep:" + " Item.pp fmt set let items (`Sum (_, l)) = l @@ -180,11 +178,11 @@ module ControlFlowCost = struct let normalize ~normalizer sum = sum |> normalized_items ~normalizer |> of_list (* Given a sum and an item, remove one occurence of the item in the sum. Returns [None] if the item is not present in the sum. - [remove_one_item ~item:A (A + B)] = B - [remove_one_item ~item:A (A + B + C)] = B + C - [remove_one_item ~item:A (A + A + B)] = A + B - [remove_one_item ~item:A (B + C)] = None - *) + [remove_one_item ~item:A (A + B)] = B + [remove_one_item ~item:A (A + B + C)] = B + C + [remove_one_item ~item:A (A + A + B)] = A + B + [remove_one_item ~item:A (B + C)] = None + *) let remove_one_item ~item (`Sum (len, l)) = match IList.remove_first l ~f:(Item.equal item) with | None -> @@ -272,11 +270,11 @@ module ControlFlowCost = struct let normalize_sums : normalizer:(elt -> elt) -> t -> unit = fun ~normalizer t -> - t.sums - <- t.sums - |> IContainer.rev_map_to_list ~fold:ARList.fold_unordered ~f:(Sum.normalize ~normalizer) - |> List.dedup_and_sort ~compare:Sum.compare - |> ARList.of_list + t.sums <- + t.sums + |> IContainer.rev_map_to_list ~fold:ARList.fold_unordered ~f:(Sum.normalize ~normalizer) + |> List.dedup_and_sort ~compare:Sum.compare + |> ARList.of_list let infer_equalities_by_removing_item ~on_infer t item = @@ -299,8 +297,8 @@ module ControlFlowCost = struct fun ~on_infer ~normalizer t -> normalize_sums ~normalizer t ; (* Keep in mind that [on_infer] can modify [t]. - It happens only if we merge a node while infering equalities from it, i.e. in the case an item appears in an equality class both alone and in two sums, i.e. X = A + X = A + B. - This is not a problem here (we could stop if it happens but it is not necessary as existing equalities still remain true after merges) *) + It happens only if we merge a node while infering equalities from it, i.e. in the case an item appears in an equality class both alone and in two sums, i.e. X = A + X = A + B. + This is not a problem here (we could stop if it happens but it is not necessary as existing equalities still remain true after merges) *) (* Also keep in mind that the current version, in the worst-case scenario, is quadratic-ish in the size of the CFG *) sum_items t |> List.iter ~f:(fun item -> infer_equalities_by_removing_item ~on_infer t item) @@ -556,9 +554,7 @@ module InstrBasicCost = struct let get_instr_cost_record tenv extras instr_node instr = match instr with | Sil.Call (ret, Exp.Const (Const.Cfun callee_pname), params, _, _) -> - let {inferbo_invariant_map; integer_type_widths; get_callee_summary_and_formals} = - extras - in + let {inferbo_invariant_map; integer_type_widths; get_callee_summary_and_formals} = extras in let operation_cost = match BufferOverrunAnalysis.extract_pre (InstrCFG.Node.id instr_node) inferbo_invariant_map diff --git a/infer/src/checkers/costModels.ml b/infer/src/checkers/costModels.ml index 9170e1cf4..2b8f21b48 100644 --- a/infer/src/checkers/costModels.ml +++ b/infer/src/checkers/costModels.ml @@ -52,8 +52,8 @@ module JavaString = struct let itv = Itv.minus (BufferOverrunDomain.Val.get_itv end_v) (BufferOverrunDomain.Val.get_itv begin_v) in - CostUtils.of_itv ~itv ~degree_kind:Polynomials.DegreeKind.Linear - ~of_function:"String.substring" location + CostUtils.of_itv ~itv ~degree_kind:Polynomials.DegreeKind.Linear ~of_function:"String.substring" + location let substring exp begin_idx model_env ~ret:_ inferbo_mem = @@ -76,8 +76,8 @@ module JavaString = struct (** O(|m|-|n|) where m is the given string and n is the index to start searching from *) - let indexOf_char_starting_from exp start_exp ({integer_type_widths; location} as model_env) - ~ret:_ inferbo_mem = + let indexOf_char_starting_from exp start_exp ({integer_type_widths; location} as model_env) ~ret:_ + inferbo_mem = let itv = CostUtils.string_len_range_itv model_env exp ~from:(Some (start_exp, integer_type_widths)) @@ -98,8 +98,8 @@ module JavaString = struct |> BufferOverrunDomain.Val.get_itv in let n = - CostUtils.of_itv ~itv ~degree_kind:Polynomials.DegreeKind.Linear - ~of_function:"String.indexOf" location + CostUtils.of_itv ~itv ~degree_kind:Polynomials.DegreeKind.Linear ~of_function:"String.indexOf" + location in let m = CostUtils.of_itv ~itv:index_itv ~degree_kind:Polynomials.DegreeKind.Linear diff --git a/infer/src/checkers/dataflow.ml b/infer/src/checkers/dataflow.ml index a9c500fa0..b349f8853 100644 --- a/infer/src/checkers/dataflow.ml +++ b/infer/src/checkers/dataflow.ml @@ -55,8 +55,8 @@ let node_throws pdesc node (proc_throws : Typ.Procname.t -> throws) : throws = | Sil.Store {e1= Exp.Lvar pvar; e2= Exp.Exn _} when is_return pvar -> (* assignment to return variable is an artifact of a throw instruction *) Throws - | Sil.Call (_, Exp.Const (Const.Cfun callee_pn), _, _, _) - when BuiltinDecl.is_declared callee_pn -> + | Sil.Call (_, Exp.Const (Const.Cfun callee_pn), _, _, _) when BuiltinDecl.is_declared callee_pn + -> if Typ.Procname.equal callee_pn BuiltinDecl.__cast then DontKnow else DoesNotThrow | Sil.Call (_, Exp.Const (Const.Cfun callee_pn), _, _, _) -> proc_throws callee_pn diff --git a/infer/src/checkers/fragmentRetainsViewChecker.ml b/infer/src/checkers/fragmentRetainsViewChecker.ml index 605419bb6..0f7dd3b08 100644 --- a/infer/src/checkers/fragmentRetainsViewChecker.ml +++ b/infer/src/checkers/fragmentRetainsViewChecker.ml @@ -51,9 +51,7 @@ let callback_fragment_retains_view_java java_pname {Callbacks.summary; exe_env} (* TODO: complain if onDestroyView is not defined, yet the Fragment has View fields *) (* TODO: handle fields nullified in callees in the same file *) let tenv = Exe_env.get_tenv exe_env (Summary.get_proc_name summary) in - let is_on_destroy_view = - String.equal (Typ.Procname.Java.get_method java_pname) on_destroy_view - in + let is_on_destroy_view = String.equal (Typ.Procname.Java.get_method java_pname) on_destroy_view in let fld_typ_is_view typ = match typ.Typ.desc with | Typ.Tptr ({desc= Tstruct tname}, _) -> diff --git a/infer/src/checkers/hoisting.ml b/infer/src/checkers/hoisting.ml index ac46dca9d..e7a9049b1 100644 --- a/infer/src/checkers/hoisting.ml +++ b/infer/src/checkers/hoisting.ml @@ -25,8 +25,8 @@ end module LoopNodes = AbstractDomain.FiniteSet (Procdesc.Node) module HoistCalls = AbstractDomain.FiniteSet (Call) -(** Map loop_header -> instrs that can be hoisted out of the loop *) module LoopHeadToHoistInstrs = Procdesc.NodeMap +(** Map loop_header -> instrs that can be hoisted out of the loop *) (* A loop-invariant function call C(args) at node N can be hoisted out of the loop if * @@ -39,7 +39,7 @@ let add_if_hoistable inv_vars instr node source_nodes idom hoistable_calls = when (* Check condition (1); N dominates all loop sources *) List.for_all ~f:(fun source -> Dominators.dominates idom node source) source_nodes && (* Check condition (2); id should be invariant already *) - LoopInvariant.InvariantVars.mem (Var.of_id ret_id) inv_vars -> + LoopInvariant.InvariantVars.mem (Var.of_id ret_id) inv_vars -> HoistCalls.add {pname; loc; node; params; ret} hoistable_calls | _ -> hoistable_calls diff --git a/infer/src/checkers/impurity.ml b/infer/src/checkers/impurity.ml index 856acaa4f..d2059c663 100644 --- a/infer/src/checkers/impurity.ml +++ b/infer/src/checkers/impurity.ml @@ -147,8 +147,7 @@ let report_errors summary modified_opt = impure_fun_ltr :: modified_ltr Formal modified_params (modified_ltr Global modified_globals []) in - Reporting.log_error summary ~loc:pname_loc ~ltr IssueType.impure_function impure_fun_desc - ) ; + Reporting.log_error summary ~loc:pname_loc ~ltr IssueType.impure_function impure_fun_desc ) ; Payload.update_summary astate summary diff --git a/infer/src/checkers/impurityDomain.ml b/infer/src/checkers/impurityDomain.ml index 3c64ef718..5c6e0a727 100644 --- a/infer/src/checkers/impurityDomain.ml +++ b/infer/src/checkers/impurityDomain.ml @@ -36,8 +36,7 @@ let join astate1 astate2 = let {modified_globals= mg2; modified_params= mp2} = astate2 in PhysEqual.optim2 ~res: - { modified_globals= ModifiedVarSet.join mg1 mg2 - ; modified_params= ModifiedVarSet.join mp1 mp2 } + {modified_globals= ModifiedVarSet.join mg1 mg2; modified_params= ModifiedVarSet.join mp1 mp2} astate1 astate2 diff --git a/infer/src/checkers/liveness.ml b/infer/src/checkers/liveness.ml index a8a2aa6d1..bc5a0437d 100644 --- a/infer/src/checkers/liveness.ml +++ b/infer/src/checkers/liveness.ml @@ -264,8 +264,7 @@ let checker {Callbacks.exe_env; summary} : Summary.t = in let report_dead_store live_vars captured_by_ref_vars = function | Sil.Store {e1= Lvar pvar; typ; e2= rhs_exp; loc} - when should_report pvar typ live_vars captured_by_ref_vars && not (is_sentinel_exp rhs_exp) - -> + when should_report pvar typ live_vars captured_by_ref_vars && not (is_sentinel_exp rhs_exp) -> log_report pvar typ loc | Sil.Call (_, e_fun, (arg, typ) :: _, loc, _) -> ( match (Exp.ignore_cast e_fun, Exp.ignore_cast arg) with diff --git a/infer/src/checkers/liveness.mli b/infer/src/checkers/liveness.mli index 06a6c2569..0a4bb464e 100644 --- a/infer/src/checkers/liveness.mli +++ b/infer/src/checkers/liveness.mli @@ -12,8 +12,8 @@ module Domain = VarSet module PreAnalysisTransferFunctions (CFG : ProcCfg.S) : TransferFunctions.SIL - with module CFG = CFG - and module Domain = Domain - and type extras = ProcData.no_extras + with module CFG = CFG + and module Domain = Domain + and type extras = ProcData.no_extras val checker : Callbacks.proc_callback_args -> Summary.t diff --git a/infer/src/checkers/loopInvariant.ml b/infer/src/checkers/loopInvariant.ml index 356dda9cb..29ce9a9d0 100644 --- a/infer/src/checkers/loopInvariant.ml +++ b/infer/src/checkers/loopInvariant.ml @@ -14,8 +14,8 @@ module VarSet = AbstractDomain.FiniteSet (Var) let debug fmt = L.(debug Analysis Medium) fmt -(** Map loop header node -> all nodes in the loop *) module LoopHeadToLoopNodes = Procdesc.NodeMap +(** Map loop header node -> all nodes in the loop *) let is_defined_outside loop_nodes reaching_defs var = ReachingDefs.ReachingDefsMap.find_opt var reaching_defs @@ -61,7 +61,7 @@ let is_def_unique_and_satisfy tenv var (loop_nodes : LoopNodes.t) ~is_pure_by_de PurityDomain.is_pure (get_purity tenv ~is_pure_by_default ~get_callee_purity callee_pname) && (* check if all params are invariant *) - List.for_all ~f:(fun (exp, _) -> is_exp_invariant exp) args + List.for_all ~f:(fun (exp, _) -> is_exp_invariant exp) args | _ -> false ) | _ -> @@ -186,9 +186,7 @@ let get_invalidated_vars_in_loop tenv loop_head ~is_pure_by_default ~get_callee_ |> Instrs.fold ~init:acc ~f:(fun acc instr -> match instr with | Sil.Call ((id, _), Const (Cfun callee_pname), args, _, _) -> ( - let purity = - get_purity tenv ~is_pure_by_default ~get_callee_purity callee_pname - in + let purity = get_purity tenv ~is_pure_by_default ~get_callee_purity callee_pname in PurityDomain.( match purity with | AbstractDomain.Types.Top -> @@ -220,8 +218,7 @@ let get_inv_vars_in_loop tenv reaching_defs_invariant_map ~is_pure_by_default ~g let process_var_once var inv_vars invalidated_vars = (* if a variable is marked invariant once, it can't be invalidated (i.e. invariance is monotonic) *) - if - InvariantVars.mem var inv_vars || Var.is_none var || InvalidatedVars.mem var invalidated_vars + if InvariantVars.mem var inv_vars || Var.is_none var || InvalidatedVars.mem var invalidated_vars then (inv_vars, false) else let loop_head_id = Procdesc.Node.get_id loop_head in @@ -263,8 +260,8 @@ let get_inv_vars_in_loop tenv reaching_defs_invariant_map ~is_pure_by_default ~g find_fixpoint InvariantVars.empty -(** Map loop head -> invariant vars in loop *) module LoopHeadToInvVars = Procdesc.NodeMap +(** Map loop head -> invariant vars in loop *) type invariant_map = VarSet.t LoopHeadToInvVars.t diff --git a/infer/src/checkers/loopInvariant.mli b/infer/src/checkers/loopInvariant.mli index 6389d0365..eb110d0f6 100644 --- a/infer/src/checkers/loopInvariant.mli +++ b/infer/src/checkers/loopInvariant.mli @@ -15,11 +15,11 @@ module LoopNodes : module type of AbstractDomain.FiniteSet (Procdesc.Node) module VarSet : module type of AbstractDomain.FiniteSet (Var) -(** Map loop header node -> all nodes in the loop *) module LoopHeadToLoopNodes = Procdesc.NodeMap +(** Map loop header node -> all nodes in the loop *) -(** Map loop head -> invariant vars in loop *) module LoopHeadToInvVars = Procdesc.NodeMap +(** Map loop head -> invariant vars in loop *) type invariant_map = VarsInLoop.t Procdesc.NodeMap.t @@ -27,9 +27,9 @@ val get_inv_vars_in_loop : Tenv.t -> ReachingDefs.invariant_map -> is_pure_by_default:bool - -> get_callee_purity:( Typ.Procname.t - -> PurityDomain.ModifiedParamIndices.t AbstractDomain.Types.top_lifted - option) + -> get_callee_purity: + ( Typ.Procname.t + -> PurityDomain.ModifiedParamIndices.t AbstractDomain.Types.top_lifted option) -> Procdesc.Node.t -> LoopNodes.t -> VarSet.t diff --git a/infer/src/checkers/purity.ml b/infer/src/checkers/purity.ml index 32dd4c44b..4c5c446ac 100644 --- a/infer/src/checkers/purity.ml +++ b/infer/src/checkers/purity.ml @@ -107,9 +107,9 @@ module TransferFunctions = struct (i.e. index of a wrt. foo's formals). void foo (int x, Object a, Object b){ - for (...){ - impure_fun(b, 10, a); // modifies only 3rd argument, i.e. a - } + for (...){ + impure_fun(b, 10, a); // modifies only 3rd argument, i.e. a + } } *) let find_params_matching_modified_args inferbo_mem formals callee_args callee_modified_params = @@ -222,9 +222,7 @@ let compute_summary summary tenv get_callee_summary inferbo_invariant_map = Procdesc.get_formals (Summary.get_proc_desc summary) |> List.map ~f:(fun (mname, _) -> Var.of_pvar (Pvar.mk mname proc_name)) in - let proc_data = - ProcData.make summary tenv {inferbo_invariant_map; formals; get_callee_summary} - in + let proc_data = ProcData.make summary tenv {inferbo_invariant_map; formals; get_callee_summary} in Analyzer.compute_post proc_data ~initial:PurityDomain.pure diff --git a/infer/src/checkers/purityModels.ml b/infer/src/checkers/purityModels.ml index 70d27c52c..671ab3c65 100644 --- a/infer/src/checkers/purityModels.ml +++ b/infer/src/checkers/purityModels.ml @@ -84,16 +84,14 @@ module ProcName = struct ; +PatternMatch.implements_io "PrintStream" &:: "print" <>--> PurityDomain.impure_global ; +PatternMatch.implements_io "PrintStream" &:: "println" <>--> PurityDomain.impure_global ; +PatternMatch.implements_io "Reader" &:: "read" <>--> PurityDomain.impure_global - ; +PatternMatch.implements_io "BufferedReader" - &:: "readLine" <>--> PurityDomain.impure_global + ; +PatternMatch.implements_io "BufferedReader" &:: "readLine" <>--> PurityDomain.impure_global (* deserialization is often expensive *) ; +PatternMatch.implements_jackson "databind.JsonDeserializer" &:: "deserialize" <>--> PurityDomain.pure ; +PatternMatch.implements_jackson "core.JsonParser" &:: "nextToken" <>--> modifies_first ; +PatternMatch.implements_jackson "core.JsonParser" &:: "getCurrentName" <>--> PurityDomain.pure - ; +PatternMatch.implements_jackson "core.JsonParser" - &::+ getStarValue <>--> PurityDomain.pure + ; +PatternMatch.implements_jackson "core.JsonParser" &::+ getStarValue <>--> PurityDomain.pure ; +PatternMatch.implements_jackson "core.JsonParser" &::+ startsWith "get" <>--> PurityDomain.pure ; +PatternMatch.implements_pseudo_collection &:: "size" <>--> PurityDomain.pure @@ -147,7 +145,6 @@ module ProcName = struct ; +PatternMatch.implements_list &:: "subList" <>--> PurityDomain.pure ; +PatternMatch.implements_arrays &:: "binarySearch" <>--> PurityDomain.pure ; +PatternMatch.implements_org_json "JSONArray" &::+ startsWith "get" <>--> PurityDomain.pure - ; +PatternMatch.implements_org_json "JSONObject" - &::+ startsWith "get" <>--> PurityDomain.pure + ; +PatternMatch.implements_org_json "JSONObject" &::+ startsWith "get" <>--> PurityDomain.pure ; +PatternMatch.implements_org_json "JSONArray" &:: "length" <>--> PurityDomain.pure ] end diff --git a/infer/src/checkers/reachingDefs.ml b/infer/src/checkers/reachingDefs.ml index a5b52999c..1f1b020b5 100644 --- a/infer/src/checkers/reachingDefs.ml +++ b/infer/src/checkers/reachingDefs.ml @@ -8,17 +8,17 @@ open! IStd module F = Format module NodeCFG = ProcCfg.Normal +module Defs = AbstractDomain.FiniteSet (Procdesc.Node) (** The node in which the reaching definition x := e is defined. A definition x :=e, declared at node N, reaches the current node if there is a path from node N to the current node such that x is not modified along the path **) -module Defs = AbstractDomain.FiniteSet (Procdesc.Node) (* even though we only add singletons (defs), the set is needed for joins *) -(** Map var -> its reaching definition *) module ReachingDefsMap = AbstractDomain.Map (Var) (Defs) +(** Map var -> its reaching definition *) (* forward transfer function for reaching definitions *) module TransferFunctionsReachingDefs (CFG : ProcCfg.S) = struct diff --git a/infer/src/checkers/reachingDefs.mli b/infer/src/checkers/reachingDefs.mli index 3ce0c383c..7f665f47b 100644 --- a/infer/src/checkers/reachingDefs.mli +++ b/infer/src/checkers/reachingDefs.mli @@ -7,15 +7,15 @@ open! IStd +module Defs : module type of AbstractDomain.FiniteSet (Procdesc.Node) (** The node in which the reaching definition x := e is defined. A definition x :=e, declared at node N, reaches the current node if there is a path from node N to the current node such that x is not modified along the path **) -module Defs : module type of AbstractDomain.FiniteSet (Procdesc.Node) -(** Map var -> its reaching definition *) module ReachingDefsMap : module type of AbstractDomain.Map (Var) (Defs) +(** Map var -> its reaching definition *) type invariant_map diff --git a/infer/src/checkers/uninit.ml b/infer/src/checkers/uninit.ml index c525e936b..2f3c947a1 100644 --- a/infer/src/checkers/uninit.ml +++ b/infer/src/checkers/uninit.ml @@ -9,8 +9,8 @@ open! IStd module F = Format module L = Logging -(** Forward analysis to compute uninitialized variables at each program point *) module D = UninitDomain.Domain +(** Forward analysis to compute uninitialized variables at each program point *) module MaybeUninitVars = UninitDomain.MaybeUninitVars module AliasedVars = AbstractDomain.FiniteSet (UninitDomain.VarPair) @@ -135,7 +135,7 @@ module TransferFunctions (CFG : ProcCfg.S) = struct (* checks that the set of initialized formal parameters defined in the precondition of - the function (init_formal_params) contains the (base of) nth formal parameter of the function *) + the function (init_formal_params) contains the (base of) nth formal parameter of the function *) let init_nth_actual_param callee_pname idx init_formal_params = match nth_formal_param callee_pname idx with | None -> @@ -231,8 +231,8 @@ module TransferFunctions (CFG : ProcCfg.S) = struct | Call (_, HilInstr.Direct call, [HilExp.AccessExpression (AddressOf (Base base))], _, _) when is_dummy_constructor_of_a_struct call -> (* if it's a default constructor, we use the following heuristic: we assume that it initializes - correctly all fields when there is an implementation of the constructor that initilizes at least one - field. If there is no explicit implementation we cannot assume fields are initialized *) + correctly all fields when there is an implementation of the constructor that initilizes at least one + field. If there is no explicit implementation we cannot assume fields are initialized *) if function_initializes_some_formal_params summary call then let maybe_uninit_vars = (* in HIL/SIL the default constructor has only one param: the struct *) @@ -327,7 +327,7 @@ module Initial = struct in base_access_expr :: flist (* for struct we take the struct address, and the access_path - to the fields one level down *) + to the fields one level down *) | _ -> acc ) | Typ.Tarray {elt} -> diff --git a/infer/src/checkers/uninitDomain.ml b/infer/src/checkers/uninitDomain.ml index 52df4a24e..ad3bda102 100644 --- a/infer/src/checkers/uninitDomain.ml +++ b/infer/src/checkers/uninitDomain.ml @@ -93,10 +93,7 @@ module VarPair = struct let pp fmt pair = F.fprintf fmt " (%a, %a)" Var.pp (fst pair) Var.pp (snd pair) end -module Record - (Domain1 : AbstractDomain.S) - (Domain2 : AbstractDomain.S) - (Domain3 : AbstractDomain.S) = +module Record (Domain1 : AbstractDomain.S) (Domain2 : AbstractDomain.S) (Domain3 : AbstractDomain.S) = struct type t = {maybe_uninit_vars: Domain1.t; aliased_vars: Domain2.t; prepost: Domain3.t prepost} @@ -158,9 +155,8 @@ end module Summary = struct (* pre = set of parameters initialized inside the procedure; - post = set of uninit local variables of the procedure *) + post = set of uninit local variables of the procedure *) type t = Domain.t prepost - let pp fmt {pre; post} = - F.fprintf fmt "@\n Pre: %a @\nPost: %a @\n" Domain.pp pre Domain.pp post + let pp fmt {pre; post} = F.fprintf fmt "@\n Pre: %a @\nPost: %a @\n" Domain.pp pre Domain.pp post end diff --git a/infer/src/clang/CType_decl.ml b/infer/src/clang/CType_decl.ml index 2a61eab1d..3348e0e08 100644 --- a/infer/src/clang/CType_decl.ml +++ b/infer/src/clang/CType_decl.ml @@ -111,13 +111,12 @@ module BuildMethodSignature = struct match decl_ref with | {Clang_ast_t.dr_name= Some {Clang_ast_t.ni_name}} -> (* In Objective-C class methods, self is not the standard self instance, since in this - context we don't have an instance. Instead it is used to get the class of the method. - We translate this variables in a different way than normal, we don't treat them as - variables in Sil, instead we remove them and get the class directly in the frontend. - For that reason, we shouldn't add them as captured variables of blocks, since they - don't appear anywhere else in the translation. *) - if is_block_inside_objc_class_method && String.equal ni_name CFrontend_config.self then - None + context we don't have an instance. Instead it is used to get the class of the method. + We translate this variables in a different way than normal, we don't treat them as + variables in Sil, instead we remove them and get the class directly in the frontend. + For that reason, we shouldn't add them as captured variables of blocks, since they + don't appear anywhere else in the translation. *) + if is_block_inside_objc_class_method && String.equal ni_name CFrontend_config.self then None else Some (Option.value_exn decl_ref.Clang_ast_t.dr_qual_type |> qual_type_to_sil_type tenv) | _ -> assert false @@ -464,8 +463,8 @@ and get_record_typename ?tenv decl = (* types that have methods. And in C++ struct/class/union can have methods *) Typ.Name.Cpp.from_qual_name Typ.NoTemplate (CAst_utils.get_qualified_name ~linters_mode name_info) - | ObjCInterfaceDecl (_, name_info, _, _, _), _ - | ObjCImplementationDecl (_, name_info, _, _, _), _ -> + | ObjCInterfaceDecl (_, name_info, _, _, _), _ | ObjCImplementationDecl (_, name_info, _, _, _), _ + -> CAst_utils.get_qualified_name name_info |> Typ.Name.Objc.from_qual_name | ObjCProtocolDecl (_, name_info, _, _, _), _ -> CAst_utils.get_qualified_name name_info |> Typ.Name.Objc.protocol_from_qual_name @@ -543,12 +542,11 @@ and mk_c_function ?tenv name function_decl_info_opt parameters = let file = match function_decl_info_opt with (* when we model static functions, we cannot take the file into account to - create a mangled name because the file of the model is different to the real file, - thus the model won't work *) + create a mangled name because the file of the model is different to the real file, + thus the model won't work *) | Some (decl_info, function_decl_info) when function_decl_info.Clang_ast_t.fdi_is_static - && not - (CTrans_models.is_modelled_static_function (QualifiedCppName.to_qual_string name)) + && not (CTrans_models.is_modelled_static_function (QualifiedCppName.to_qual_string name)) -> let file_opt = (fst decl_info.Clang_ast_t.di_source_range).Clang_ast_t.sl_file @@ -721,7 +719,7 @@ and get_record_struct_type tenv definition_decl : Typ.desc = sil_desc ) else ( (* There is no definition for that struct in whole translation unit. - Put empty struct into tenv to prevent backend problems *) + Put empty struct into tenv to prevent backend problems *) ignore (Tenv.mk_struct tenv ~fields:[] sil_typename) ; CAst_utils.update_sil_types_map type_ptr sil_desc ; sil_desc ) ) diff --git a/infer/src/clang/Capture.ml b/infer/src/clang/Capture.ml index 828d35410..dc7c608f4 100644 --- a/infer/src/clang/Capture.ml +++ b/infer/src/clang/Capture.ml @@ -183,8 +183,7 @@ let cc1_capture clang_cmd = else if Config.skip_analysis_in_path_skips_compilation && CLocation.is_file_blacklisted source_path then ( - L.(debug Capture Quiet) - "@\n Skip compilation and analysis of source file %s@\n@\n" source_path ; + L.(debug Capture Quiet) "@\n Skip compilation and analysis of source file %s@\n@\n" source_path ; () ) else match Config.clang_biniou_file with diff --git a/infer/src/clang/ClangCommand.ml b/infer/src/clang/ClangCommand.ml index 5a55403cb..42a225fcd 100644 --- a/infer/src/clang/ClangCommand.ml +++ b/infer/src/clang/ClangCommand.ml @@ -16,8 +16,7 @@ type t = ; is_driver: bool } let fcp_dir = - Config.bin_dir ^/ Filename.parent_dir_name ^/ Filename.parent_dir_name - ^/ "facebook-clang-plugins" + Config.bin_dir ^/ Filename.parent_dir_name ^/ Filename.parent_dir_name ^/ "facebook-clang-plugins" (** path of the plugin to load in clang *) @@ -189,8 +188,7 @@ let clang_cc1_cmd_sanitizer cmd = for details on the effects of setting SDKROOT *) let implicit_sysroot = if not explicit_sysroot_passed then - Option.map Config.implicit_sdk_root ~f:(fun x -> ["-isysroot"; x]) - |> Option.value ~default:[] + Option.map Config.implicit_sdk_root ~f:(fun x -> ["-isysroot"; x]) |> Option.value ~default:[] else [] in let pre_args_rev = [] |> List.rev_append implicit_sysroot in @@ -199,10 +197,10 @@ let clang_cc1_cmd_sanitizer cmd = |> List.rev_append ["-include"; Config.lib_dir ^/ "clang_wrappers" ^/ "global_defines.h"] |> List.rev_append args_defines |> (* Never error on warnings. Clang is often more strict than Apple's version. These arguments - are appended at the end to override previous opposite settings. How it's done: suppress - all the warnings, since there are no warnings, compiler can't elevate them to error - level. *) - argv_cons "-Wno-everything" + are appended at the end to override previous opposite settings. How it's done: suppress + all the warnings, since there are no warnings, compiler can't elevate them to error + level. *) + argv_cons "-Wno-everything" in let clang_arguments = filter_and_replace_unsupported_args ~replace_options_arg ~post_args:(List.rev post_args_rev) @@ -247,14 +245,14 @@ let with_plugin_args args = let args_before_rev = [] |> (* -cc1 has to be the first argument or clang will think it runs in driver mode *) - argv_cons "-cc1" + argv_cons "-cc1" |> List.rev_append [ "-load" ; plugin_path ; (* (t7400979) this is a workaround to avoid that clang crashes when the -fmodules flag and the - YojsonASTExporter plugin are used. Since the -plugin argument disables the generation of .o - files, we invoke apple clang again to generate the expected artifacts. This will keep - xcodebuild plus all the sub-steps happy. *) + YojsonASTExporter plugin are used. Since the -plugin argument disables the generation of .o + files, we invoke apple clang again to generate the expected artifacts. This will keep + xcodebuild plus all the sub-steps happy. *) (if has_flag args "-fmodules" then "-plugin" else "-add-plugin") ; plugin_name ; plugin_arg_flag diff --git a/infer/src/clang/ClangWrapper.ml b/infer/src/clang/ClangWrapper.ml index b3a6b910d..4f9acfb35 100644 --- a/infer/src/clang/ClangWrapper.ml +++ b/infer/src/clang/ClangWrapper.ml @@ -5,10 +5,10 @@ * LICENSE file in the root directory of this source tree. *) +open! IStd (** Given a clang command, normalize it via `clang -###` if needed to get a clear view of what work is being done and which source files are being compiled, if any, then replace compilation commands by our own clang with our plugin attached for each source file. *) -open! IStd module L = Logging @@ -37,7 +37,7 @@ let check_for_existing_file args = | option :: rest -> if String.equal option "-c" then (* infer-capture-all flavour of buck produces path to generated file that doesn't exist. - Create empty file empty file and pass that to clang. This is to enable compilation to continue *) + Create empty file empty file and pass that to clang. This is to enable compilation to continue *) match (clang_ignore_regex, List.hd rest) with | Some regexp, Some arg -> if Str.string_match regexp arg 0 && Sys.file_exists arg <> `Yes then ( @@ -59,27 +59,27 @@ let clang_driver_action_items : ClangCommand.t -> action_item list = Printf.sprintf "%s 2>&1" ( ClangCommand.prepend_arg "-###" cmd |> (* c++ modules are not supported, so let clang know in case it was passed "-fmodules". - Unfortunately we cannot know accurately if "-fmodules" was passed because we don't go - into argument files at this point ("clang -### ..." will do that for us), so we also pass - "-Qunused-arguments" to silence the potential warning that "-fno-cxx-modules" was - ignored. Moreover, "-fno-cxx-modules" is only accepted by the clang driver so we have to - pass it now. - - Using clang instead of gcc may trigger warnings about unsupported optimization flags; - passing -Wno-ignored-optimization-argument prevents that. - - Clang adds "-faddrsig" by default on ELF targets. This is ok in itself, but for some - reason that flag is the only one to show up *after* the source file name in the -cc1 - commands emitted by [clang -### ...]. Passing [-fno-addrsig] ensures that the source - path is always the last argument. *) - ClangCommand.append_args - [ "-fno-cxx-modules" - ; "-Qunused-arguments" - ; "-Wno-ignored-optimization-argument" - ; "-fno-addrsig" ] + Unfortunately we cannot know accurately if "-fmodules" was passed because we don't go + into argument files at this point ("clang -### ..." will do that for us), so we also pass + "-Qunused-arguments" to silence the potential warning that "-fno-cxx-modules" was + ignored. Moreover, "-fno-cxx-modules" is only accepted by the clang driver so we have to + pass it now. + + Using clang instead of gcc may trigger warnings about unsupported optimization flags; + passing -Wno-ignored-optimization-argument prevents that. + + Clang adds "-faddrsig" by default on ELF targets. This is ok in itself, but for some + reason that flag is the only one to show up *after* the source file name in the -cc1 + commands emitted by [clang -### ...]. Passing [-fno-addrsig] ensures that the source + path is always the last argument. *) + ClangCommand.append_args + [ "-fno-cxx-modules" + ; "-Qunused-arguments" + ; "-Wno-ignored-optimization-argument" + ; "-fno-addrsig" ] |> (* If -fembed-bitcode is passed, it leads to multiple cc1 commands, which try to read .bc files that don't get generated, and fail. So pass -fembed-bitcode=off to disable. *) - ClangCommand.append_args ["-fembed-bitcode=off"] + ClangCommand.append_args ["-fembed-bitcode=off"] |> ClangCommand.command_to_run ) in L.(debug Capture Medium) "clang -### invocation: %s@\n" clang_hashhashhash ; @@ -89,8 +89,9 @@ let clang_driver_action_items : ClangCommand.t -> action_item list = CanonicalCommand ( (* massage line to remove edge-cases for splitting *) match - "\"" ^ line ^ " \"" |> (* split by whitespace *) - Str.split (Str.regexp_string "\" \"") + "\"" ^ line ^ " \"" + |> (* split by whitespace *) + Str.split (Str.regexp_string "\" \"") with | prog :: args -> ClangCommand.mk ~is_driver:false ClangQuotes.EscapedDoubleQuotes ~prog ~args @@ -112,8 +113,7 @@ let clang_driver_action_items : ClangCommand.t -> action_item list = let line = In_channel.input_line_exn i in (* keep only commands and errors *) if - Str.string_match commands_or_errors line 0 - && not (Str.string_match ignored_errors line 0) + Str.string_match commands_or_errors line 0 && not (Str.string_match ignored_errors line 0) then normalized_commands := one_line line :: !normalized_commands done with End_of_file -> () @@ -134,7 +134,7 @@ let normalize ~prog ~args : action_item list = let exec_action_item ~prog ~args = function | ClangError error -> (* An error in the output of `clang -### ...`. Outputs the error and fail. This is because - `clang -###` pretty much never fails, but warns of failures on stderr instead. *) + `clang -###` pretty much never fails, but warns of failures on stderr instead. *) L.(die UserError) "Failed to execute compilation command:@\n\ '%s' %a@\n\ @@ -142,8 +142,7 @@ let exec_action_item ~prog ~args = function Error message:@\n\ %s@\n\ @\n\ - *** Infer needs a working compilation command to run." - prog Pp.cli_args args error + *** Infer needs a working compilation command to run." prog Pp.cli_args args error | ClangWarning warning -> L.external_warning "%s@\n" warning | CanonicalCommand clang_cmd -> @@ -184,8 +183,8 @@ let exe ~prog ~args = In particular, this can happen when - there are only assembly commands to execute, which we skip, or - the user tries to run `infer -- clang -c file_that_does_not_exist.c`. In this case, this - will fail with the appropriate error message from clang instead of silently analyzing 0 - files. *) + will fail with the appropriate error message from clang instead of silently analyzing 0 + files. *) L.(debug Capture Quiet) "WARNING: `clang -### ` returned an empty set of commands to run and no error. Will \ run the original command directly:@\n\ diff --git a/infer/src/clang/ast_expressions.ml b/infer/src/clang/ast_expressions.ml index f55270d06..b34d57a91 100644 --- a/infer/src/clang/ast_expressions.ml +++ b/infer/src/clang/ast_expressions.ml @@ -128,9 +128,7 @@ let make_message_expr param_qt selector decl_ref_exp stmt_info add_cast = let stmt_info = stmt_info_with_fresh_pointer stmt_info in let parameters = if add_cast then - let cast_expr = - create_implicit_cast_expr stmt_info [decl_ref_exp] param_qt `LValueToRValue - in + let cast_expr = create_implicit_cast_expr stmt_info [decl_ref_exp] param_qt `LValueToRValue in [cast_expr] else [decl_ref_exp] in diff --git a/infer/src/clang/cArithmetic_trans.ml b/infer/src/clang/cArithmetic_trans.ml index 2ad9319ed..e84273d75 100644 --- a/infer/src/clang/cArithmetic_trans.ml +++ b/infer/src/clang/cArithmetic_trans.ml @@ -178,8 +178,7 @@ let unary_operation_instruction translation_unit_context uoi e typ loc = let uok = Clang_ast_j.string_of_unary_operator_kind uoi.Clang_ast_t.uoi_kind in L.(debug Capture Medium) "@\n\ - WARNING: Missing translation for Unary Operator Kind %s. The construct has been \ - ignored...@\n" + WARNING: Missing translation for Unary Operator Kind %s. The construct has been ignored...@\n" uok ; (e, []) diff --git a/infer/src/clang/cAst_utils.ml b/infer/src/clang/cAst_utils.ml index cbd6ea155..979072d67 100644 --- a/infer/src/clang/cAst_utils.ml +++ b/infer/src/clang/cAst_utils.ml @@ -30,7 +30,7 @@ let get_qualified_name ?(linters_mode = false) name_info = if not linters_mode then get_qual_name name_info.Clang_ast_t.ni_qual_name else (* Because we are in linters mode, we can't get precise info about templates, - so we strip the template characters to not upset invariants in the system. *) + so we strip the template characters to not upset invariants in the system. *) let replace_template_chars qual_name = String.tr ~target:'<' ~replacement:'_' qual_name |> String.tr ~target:'>' ~replacement:'_' in @@ -149,15 +149,13 @@ let update_enum_map enum_constant_pointer sil_exp = in let enum_map_value = (predecessor_pointer_opt, Some sil_exp) in CFrontend_config.enum_map := - ClangPointers.Map.set !CFrontend_config.enum_map ~key:enum_constant_pointer - ~data:enum_map_value + ClangPointers.Map.set !CFrontend_config.enum_map ~key:enum_constant_pointer ~data:enum_map_value let add_enum_constant enum_constant_pointer predecessor_pointer_opt = let enum_map_value = (predecessor_pointer_opt, None) in CFrontend_config.enum_map := - ClangPointers.Map.set !CFrontend_config.enum_map ~key:enum_constant_pointer - ~data:enum_map_value + ClangPointers.Map.set !CFrontend_config.enum_map ~key:enum_constant_pointer ~data:enum_map_value let get_enum_constant_exp enum_constant_pointer = @@ -236,7 +234,7 @@ let name_opt_of_typedef_qual_type qual_type = let qual_type_of_decl_ptr decl_ptr = { (* This function needs to be in this module - CAst_utils can't depend on - Ast_expressions *) + Ast_expressions *) Clang_ast_t.qt_type_ptr= Clang_ast_extend.DeclPtr decl_ptr ; qt_is_const= false ; qt_is_volatile= false @@ -576,8 +574,8 @@ let get_superclass_curr_class_objc_from_decl (decl : Clang_ast_t.decl) = otdi.otdi_super | _ -> Logging.die InternalError - "Expected that ObjCImplementationDecl always has a pointer to it's interface, but \ - wasn't the case with %s" + "Expected that ObjCImplementationDecl always has a pointer to it's interface, but wasn't \ + the case with %s" ni.Clang_ast_t.ni_name ) | ObjCCategoryDecl (_, _, _, _, ocdi) -> ocdi.odi_class_interface diff --git a/infer/src/clang/cAst_utils.mli b/infer/src/clang/cAst_utils.mli index 50d126468..9c21662f5 100644 --- a/infer/src/clang/cAst_utils.mli +++ b/infer/src/clang/cAst_utils.mli @@ -23,8 +23,7 @@ val get_stmt : Clang_ast_t.pointer -> Clang_ast_t.source_range -> Clang_ast_t.st val get_stmt_exn : Clang_ast_t.pointer -> Clang_ast_t.source_range -> Clang_ast_t.stmt -val get_stmt_opt : - Clang_ast_t.pointer option -> Clang_ast_t.source_range -> Clang_ast_t.stmt option +val get_stmt_opt : Clang_ast_t.pointer option -> Clang_ast_t.source_range -> Clang_ast_t.stmt option val get_decl_opt_with_decl_ref : Clang_ast_t.decl_ref option -> Clang_ast_t.decl option @@ -111,8 +110,7 @@ val get_super_ObjCImplementationDecl : Clang_ast_t.obj_c_implementation_decl_info -> Clang_ast_t.decl option (** Given an objc impl decl info, return its super class implementation decl *) -val is_objc_if_descendant : - ?blacklist:string list -> Clang_ast_t.decl option -> string list -> bool +val is_objc_if_descendant : ?blacklist:string list -> Clang_ast_t.decl option -> string list -> bool (** Recursively go up the inheritance hierarchy of a given ObjCInterfaceDecl. Returns true if the passed in decl is an objc interface decl that's an eventual descendant of one of the classes passed in. diff --git a/infer/src/clang/cFrontend_config.ml b/infer/src/clang/cFrontend_config.ml index 961f4e01e..e528afbf9 100644 --- a/infer/src/clang/cFrontend_config.ml +++ b/infer/src/clang/cFrontend_config.ml @@ -47,8 +47,8 @@ let ckcomponentcontroller_cl = "CKComponentController" (** script to run our own clang *) let clang_bin xx = - Config.bin_dir ^/ Filename.parent_dir_name ^/ Filename.parent_dir_name - ^/ "facebook-clang-plugins" ^/ "clang" ^/ "install" ^/ "bin" ^/ "clang" ^ xx + Config.bin_dir ^/ Filename.parent_dir_name ^/ Filename.parent_dir_name ^/ "facebook-clang-plugins" + ^/ "clang" ^/ "install" ^/ "bin" ^/ "clang" ^ xx let class_method = "class" diff --git a/infer/src/clang/cFrontend_decl.ml b/infer/src/clang/cFrontend_decl.ml index b11c5a005..7836eff72 100644 --- a/infer/src/clang/cFrontend_decl.ml +++ b/infer/src/clang/cFrontend_decl.ml @@ -41,8 +41,8 @@ module CFrontend_decl_funct (T : CModule_type.CTranslation) : CModule_type.CFron (Typ.Procname.to_string procname) ; let vars_to_destroy = CScope.Variables.compute_vars_to_destroy_map body in let context = - CContext.create_context trans_unit_ctx tenv cfg procdesc class_decl_opt - has_return_param outer_context_opt vars_to_destroy + CContext.create_context trans_unit_ctx tenv cfg procdesc class_decl_opt has_return_param + outer_context_opt vars_to_destroy in let start_node = Procdesc.get_start_node procdesc in let exit_node = Procdesc.get_exit_node procdesc in @@ -261,9 +261,7 @@ module CFrontend_decl_funct (T : CModule_type.CTranslation) : CModule_type.CFron let method_matcher = QualifiedCppName.Match.of_fuzzy_qual_names Config.whitelisted_cpp_methods in - let class_matcher = - QualifiedCppName.Match.of_fuzzy_qual_names Config.whitelisted_cpp_classes - in + let class_matcher = QualifiedCppName.Match.of_fuzzy_qual_names Config.whitelisted_cpp_classes in fun qual_name -> (* either the method is explictely whitelisted, or the whole class is whitelisted *) QualifiedCppName.Match.match_qualifiers method_matcher qual_name @@ -378,10 +376,10 @@ module CFrontend_decl_funct (T : CModule_type.CTranslation) : CModule_type.CFron when String.is_prefix ~prefix:"__infer_" named_decl_info.ni_name || (vdi_is_global && Option.is_some vdi_init_expr) -> (* create a fake procedure that initializes the global variable so that the variable - initializer can be analyzed by the backend (eg, the SIOF checker) *) + initializer can be analyzed by the backend (eg, the SIOF checker) *) let procname = (* create the corresponding global variable to get the right pname for its - initializer *) + initializer *) let global = CGeneral_utils.mk_sil_global_var trans_unit_ctx decl_info named_decl_info vdi qt in @@ -393,15 +391,14 @@ module CFrontend_decl_funct (T : CModule_type.CTranslation) : CModule_type.CFron decl_info.Clang_ast_t.di_source_range ClangMethodKind.C_FUNCTION None None None `None in let stmt_info = - { si_pointer= CAst_utils.get_fresh_pointer () - ; si_source_range= decl_info.di_source_range } + {si_pointer= CAst_utils.get_fresh_pointer (); si_source_range= decl_info.di_source_range} in let body = Clang_ast_t.DeclStmt (stmt_info, [], [dec]) in ignore (CMethod_trans.create_local_procdesc trans_unit_ctx cfg tenv ms [body] []) ; add_method trans_unit_ctx tenv cfg CContext.ContextNoCls procname body ms None None [] (* Note that C and C++ records are treated the same way - Skip translating implicit struct declarations, unless they have - full definition (which happens with C++ lambdas) *) + Skip translating implicit struct declarations, unless they have + full definition (which happens with C++ lambdas) *) | ClassTemplateSpecializationDecl (di, _, _, decl_list, _, _, rdi, _, _, _) | CXXRecordDecl (di, _, _, decl_list, _, _, rdi, _) | RecordDecl (di, _, _, decl_list, _, _, rdi) diff --git a/infer/src/clang/cFrontend_errors.ml b/infer/src/clang/cFrontend_errors.ml index dedc42225..eea0aae47 100644 --- a/infer/src/clang/cFrontend_errors.ml +++ b/infer/src/clang/cFrontend_errors.ml @@ -36,8 +36,8 @@ let protect ~f ~recover ~pp_context (trans_unit_ctx : CFrontend_config.translati in try f () with (* Always keep going in case of known limitations of the frontend, crash otherwise (by not - catching the exception) unless `--keep-going` was passed. Print errors we should fix - (t21762295) to the console. *) + catching the exception) unless `--keep-going` was passed. Print errors we should fix + (t21762295) to the console. *) | Unimplemented e -> ClangLogging.log_caught_exception trans_unit_ctx "Unimplemented" e.position e.source_range e.ast_node ; diff --git a/infer/src/clang/cGeneral_utils.ml b/infer/src/clang/cGeneral_utils.ml index c79dafd4e..c92134351 100644 --- a/infer/src/clang/cGeneral_utils.ml +++ b/infer/src/clang/cGeneral_utils.ml @@ -132,8 +132,7 @@ let mk_sil_global_var {CFrontend_config.source_file} ?(mk_name = fun _ x -> x) d None ) |> Option.value_map ~default:true ~f:(function | Clang_ast_t.CXXRecordDecl (_, _, _, _, _, _, _, {xrdi_is_pod}) - | Clang_ast_t.ClassTemplateSpecializationDecl (_, _, _, _, _, _, _, {xrdi_is_pod}, _, _) - -> + | Clang_ast_t.ClassTemplateSpecializationDecl (_, _, _, _, _, _, _, {xrdi_is_pod}, _, _) -> xrdi_is_pod | _ -> true ) @@ -152,9 +151,7 @@ let mk_sil_global_var {CFrontend_config.source_file} ?(mk_name = fun _ x -> x) d let mk_sil_var trans_unit_ctx named_decl_info decl_info_qual_type_opt procname outer_procname = match decl_info_qual_type_opt with | Some (decl_info, qt, var_decl_info, should_be_mangled) -> - let name_string, simple_name = - get_var_name_mangled decl_info named_decl_info var_decl_info - in + let name_string, simple_name = get_var_name_mangled decl_info named_decl_info var_decl_info in if var_decl_info.Clang_ast_t.vdi_is_global then let mk_name = if var_decl_info.Clang_ast_t.vdi_is_static_local then diff --git a/infer/src/clang/cGeneral_utils.mli b/infer/src/clang/cGeneral_utils.mli index e75123b12..d3e174ce0 100644 --- a/infer/src/clang/cGeneral_utils.mli +++ b/infer/src/clang/cGeneral_utils.mli @@ -16,8 +16,7 @@ val add_no_duplicates_fields : Typ.Struct.field -> Typ.Struct.field list -> Typ. val append_no_duplicates_fields : Typ.Struct.field list -> Typ.Struct.field list -> Typ.Struct.field list -val append_no_duplicates_methods : - Typ.Procname.t list -> Typ.Procname.t list -> Typ.Procname.t list +val append_no_duplicates_methods : Typ.Procname.t list -> Typ.Procname.t list -> Typ.Procname.t list val swap_elements_list : 'a list -> 'a list diff --git a/infer/src/clang/cLocation.ml b/infer/src/clang/cLocation.ml index 9b158dc68..fab476f20 100644 --- a/infer/src/clang/cLocation.ml +++ b/infer/src/clang/cLocation.ml @@ -44,8 +44,7 @@ let should_do_frontend_check translation_unit (loc_start, _) = translate the headers that are part of the project. However, in testing mode, we don't want to translate the headers because the dot files in the frontend tests should contain nothing else than the source file to avoid conflicts between different versions of the libraries. *) -let should_translate translation_unit (loc_start, loc_end) decl_trans_context ~translate_when_used - = +let should_translate translation_unit (loc_start, loc_end) decl_trans_context ~translate_when_used = let map_file_of pred loc = match Option.map ~f:SourceFile.from_abs_path loc.Clang_ast_t.sl_file with | Some f -> diff --git a/infer/src/clang/cMethodSignature.ml b/infer/src/clang/cMethodSignature.ml index b93b12b3b..1b43b6158 100644 --- a/infer/src/clang/cMethodSignature.ml +++ b/infer/src/clang/cMethodSignature.ml @@ -48,9 +48,9 @@ let is_setter {pointer_to_property_opt; params} = Option.is_some pointer_to_property_opt && Int.equal (List.length params) 1 -let mk name class_param params ret_type ?(has_added_return_param = false) attributes loc - method_kind ?(is_cpp_virtual = false) ?(is_cpp_nothrow = false) ?(is_variadic = false) - pointer_to_parent pointer_to_property_opt return_param_typ access = +let mk name class_param params ret_type ?(has_added_return_param = false) attributes loc method_kind + ?(is_cpp_virtual = false) ?(is_cpp_nothrow = false) ?(is_variadic = false) pointer_to_parent + pointer_to_property_opt return_param_typ access = { name ; access ; class_param diff --git a/infer/src/clang/cMethod_trans.ml b/infer/src/clang/cMethod_trans.ml index 18dde7387..0c6ede171 100644 --- a/infer/src/clang/cMethod_trans.ml +++ b/infer/src/clang/cMethod_trans.ml @@ -127,8 +127,8 @@ let sil_func_attributes_of_attributes attrs = match al with | [] -> List.rev acc - | `SentinelAttr (_attr_info, {Clang_ast_t.sai_sentinel= sentinel; sai_null_pos= null_pos}) - :: tl -> + | `SentinelAttr (_attr_info, {Clang_ast_t.sai_sentinel= sentinel; sai_null_pos= null_pos}) :: tl + -> do_translation (PredSymb.FA_sentinel (sentinel, null_pos) :: acc) tl | _ :: tl -> do_translation acc tl @@ -228,9 +228,7 @@ let create_local_procdesc ?(set_objc_accessor_attr = false) trans_unit_ctx cfg t let captured_mangled = List.map ~f:(fun (var, t) -> (Pvar.get_name var, t)) captured in (* Captured variables for blocks are treated as parameters *) let formals = captured_mangled @ formals in - let const_formals = - get_const_params_indices ~shift:(List.length captured_mangled) all_params - in + let const_formals = get_const_params_indices ~shift:(List.length captured_mangled) all_params in let source_range = ms.CMethodSignature.loc in L.(debug Capture Verbose) "@\nCreating a new procdesc for function: '%a'@\n@." Typ.Procname.pp proc_name ; diff --git a/infer/src/clang/cScope.ml b/infer/src/clang/cScope.ml index 3c417d2bc..d41254db9 100644 --- a/infer/src/clang/cScope.ml +++ b/infer/src/clang/cScope.ml @@ -164,7 +164,7 @@ module Variables = struct List.filter decl_list ~f:(function Clang_ast_t.VarDecl _ -> true | _ -> false) in (* the reverse order is the one we want to destroy the variables in at the end of the scope - *) + *) L.debug Capture Verbose "+%a@," (Pp.seq ~sep:"," pp_var_decl) new_vars ; (rev_append new_vars scope, map) | _ -> ( diff --git a/infer/src/clang/cTrans.ml b/infer/src/clang/cTrans.ml index ce9fba9ff..6dc6e385e 100644 --- a/infer/src/clang/cTrans.ml +++ b/infer/src/clang/cTrans.ml @@ -214,8 +214,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s let pdesc = context.procdesc in let attr = Procdesc.get_attributes pdesc in let procname = Procdesc.get_proc_name pdesc in - attr.formals (* remove this, which should always be the first formal parameter *) - |> List.tl_exn + attr.formals (* remove this, which should always be the first formal parameter *) |> List.tl_exn |> List.fold_left ~init:([], []) ~f:(fun (forwarded_params, forwarded_init_exps) (formal, typ) -> let pvar = Pvar.mk formal procname in @@ -225,8 +224,8 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s :: forwarded_init_exps ) ) - let create_call_instr trans_state (return_type : Typ.t) function_sil params_sil sil_loc - call_flags ~is_objc_method ~is_inherited_ctor = + let create_call_instr trans_state (return_type : Typ.t) function_sil params_sil sil_loc call_flags + ~is_objc_method ~is_inherited_ctor = let ret_id_typ = (Ident.create_fresh Ident.knormal, return_type) in let ret_id', params, initd_exps, ret_exps, call_flags = (* Assumption: should_add_return_param will return true only for struct types *) @@ -274,7 +273,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s , params_sil , [] , (let i, t = ret_id_typ in - (Exp.Var i, t)) + (Exp.Var i, t) ) , call_flags ) in let forwarded_params, forwarded_init_instrs = @@ -562,9 +561,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s else (field_exp, []) in let instrs = pre_trans_result.control.instrs @ deref_instrs in - { pre_trans_result with - control= {pre_trans_result.control with instrs} - ; return= (exp, field_typ) } + {pre_trans_result with control= {pre_trans_result.control with instrs}; return= (exp, field_typ)} type decl_ref_context = MemberOrIvar of trans_result | DeclRefExpr @@ -604,7 +601,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s with | MemberOrIvar {return= (exp, {Typ.desc= Tptr (typ, _)}) as return} (* We need to add a dereference before a method call to find null dereferences when - calling a method with null *) + calling a method with null *) when decl_kind <> `CXXConstructor -> let no_id = Ident.create_none () in let extra_instrs = [Sil.Load {id= no_id; e= exp; root_typ= typ; typ; loc= sil_loc}] in @@ -996,9 +993,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s let context = trans_state.context in let fn_type_no_ref = CType_decl.get_type_from_expr_info expr_info context.CContext.tenv in let function_type = add_reference_if_glvalue fn_type_no_ref expr_info in - let sil_loc = - CLocation.location_of_stmt_info context.translation_unit_context.source_file si - in + let sil_loc = CLocation.location_of_stmt_info context.translation_unit_context.source_file si in (* First stmt is the function expr and the rest are params *) let fun_exp_stmt, params_stmt = match stmt_list with fe :: params -> (fe, params) | _ -> assert false @@ -1023,8 +1018,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s (* we cannot translate the arguments of __builtin_object_size because preprocessing copies them verbatim from a call to a different function, and they might be side-effecting *) let should_translate_args = - not - (Option.value_map ~f:CTrans_models.is_builtin_object_size ~default:false callee_pname_opt) + not (Option.value_map ~f:CTrans_models.is_builtin_object_size ~default:false callee_pname_opt) in let params_stmt = if should_translate_args then params_stmt else [] in (* As we may have nodes coming from different parameters we need to *) @@ -1061,9 +1055,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s let context = trans_state.context in let fn_type_no_ref = CType_decl.get_type_from_expr_info expr_info context.CContext.tenv in let function_type = add_reference_if_glvalue fn_type_no_ref expr_info in - let sil_loc = - CLocation.location_of_stmt_info context.translation_unit_context.source_file si - in + let sil_loc = CLocation.location_of_stmt_info context.translation_unit_context.source_file si in let trans_state_pri = PriorityNode.try_claim_priority_node trans_state si in let sil_fe = Exp.Const (Const.Cfun BuiltinDecl.__builtin_va_arg) in let trans_state_param = {trans_state_pri with succ_nodes= []; var_exp_typ= None} in @@ -1082,9 +1074,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s function_type ~is_cpp_call_virtual ~is_injected_destructor extra_res_trans ~is_inherited_ctor = let context = trans_state_pri.context in - let sil_loc = - CLocation.location_of_stmt_info context.translation_unit_context.source_file si - in + let sil_loc = CLocation.location_of_stmt_info context.translation_unit_context.source_file si in let callee_pname = Option.value_exn result_trans_callee.method_name in (* As we may have nodes coming from different parameters we need to call instruction for each parameter and collect the results afterwards. The 'instructions' function does not do that *) @@ -1137,9 +1127,8 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s let is_cpp_call_virtual = result_trans_callee.is_cpp_call_virtual in let fn_type_no_ref = CType_decl.get_type_from_expr_info expr_info context.CContext.tenv in let function_type = add_reference_if_glvalue fn_type_no_ref expr_info in - cxx_method_construct_call_trans trans_state_pri result_trans_callee params_stmt si - function_type ~is_injected_destructor:false ~is_cpp_call_virtual None - ~is_inherited_ctor:false + cxx_method_construct_call_trans trans_state_pri result_trans_callee params_stmt si function_type + ~is_injected_destructor:false ~is_cpp_call_virtual None ~is_inherited_ctor:false and cxxConstructExpr_trans trans_state si params_stmt ei cxx_constr_info ~is_inherited_ctor = @@ -1169,15 +1158,15 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s decl_ref_trans ~context:(MemberOrIvar this_res_trans) trans_state si decl_ref in let res_trans = - cxx_method_construct_call_trans trans_state_pri res_trans_callee params_stmt si - (Typ.mk Tvoid) ~is_injected_destructor:false ~is_cpp_call_virtual:false - (Some tmp_res_trans) ~is_inherited_ctor + cxx_method_construct_call_trans trans_state_pri res_trans_callee params_stmt si (Typ.mk Tvoid) + ~is_injected_destructor:false ~is_cpp_call_virtual:false (Some tmp_res_trans) + ~is_inherited_ctor in {res_trans with return= tmp_res_trans.return} - and cxx_destructor_call_trans trans_state si this_res_trans class_type_ptr - ~is_injected_destructor ~is_inner_destructor = + and cxx_destructor_call_trans trans_state si this_res_trans class_type_ptr ~is_injected_destructor + ~is_inner_destructor = (* cxx_method_construct_call_trans claims a priority with the same `si`. A new pointer is generated to avoid premature node creation *) let si' = {si with Clang_ast_t.si_pointer= CAst_utils.get_fresh_pointer ()} in @@ -1211,8 +1200,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s CMethod_trans.get_class_name_method_call_from_receiver_kind context obj_c_message_expr_info act_params in - if trans_state.is_fst_arg_objc_instance_method_call && is_receiver_instance receiver_kind - then + if trans_state.is_fst_arg_objc_instance_method_call && is_receiver_instance receiver_kind then raise (Self.SelfClassException {class_name; position= __POS__; source_range= si.Clang_ast_t.si_source_range}) @@ -1221,8 +1209,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s Some (mk_trans_result (exp, typ) empty_control) else if (* alloc or new *) - String.equal selector CFrontend_config.alloc - || String.equal selector CFrontend_config.new_str + String.equal selector CFrontend_config.alloc || String.equal selector CFrontend_config.new_str then match receiver_kind with | `Class qual_type -> @@ -1268,9 +1255,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s " priority node free = '%s'@\n@." (string_of_bool (PriorityNode.is_priority_free trans_state)) ; let context = trans_state.context in - let sil_loc = - CLocation.location_of_stmt_info context.translation_unit_context.source_file si - in + let sil_loc = CLocation.location_of_stmt_info context.translation_unit_context.source_file si in let method_type_no_ref = CType_decl.get_type_from_expr_info expr_info context.CContext.tenv in let method_type = add_reference_if_glvalue method_type_no_ref expr_info in let trans_state_pri = PriorityNode.try_claim_priority_node trans_state si in @@ -1533,8 +1518,8 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s in let var_typ = add_reference_if_glvalue typ expr_info in let join_node = - Procdesc.create_node trans_state.context.CContext.procdesc sil_loc - Procdesc.Node.Join_node [] + Procdesc.create_node trans_state.context.CContext.procdesc sil_loc Procdesc.Node.Join_node + [] in Procdesc.node_set_succs_exn context.procdesc join_node succ_nodes [] ; let pvar = CVar_decl.mk_temp_sil_var procdesc ~name:"SIL_temp_conditional___" in @@ -1622,9 +1607,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s L.(debug Capture Verbose) " No short-circuit condition@\n" ; let res_trans_cond = if is_null_stmt cond then - mk_trans_result - (Exp.Const (Const.Cint IntLit.one), Typ.mk (Tint Typ.IBool)) - empty_control + mk_trans_result (Exp.Const (Const.Cint IntLit.one), Typ.mk (Tint Typ.IBool)) empty_control (* Assumption: If it's a null_stmt, it is a loop with no bound, so we set condition to 1 *) else if is_cmp then let open Clang_ast_t in @@ -1700,8 +1683,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s ; instrs= res_trans_s1.control.instrs @ res_trans_s2.control.instrs ; initd_exps= [] } in - L.(debug Capture Verbose) - "Translating Condition for If-then-else/Loop/Conditional Operator @\n" ; + L.(debug Capture Verbose) "Translating Condition for If-then-else/Loop/Conditional Operator @\n" ; let open Clang_ast_t in match cond with | BinaryOperator (_, [s1; s2], _, boi) -> ( @@ -1794,9 +1776,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s match if_stmt_info.isi_init with | Some init_stmt_ptr -> let init_stmt = CAst_utils.get_stmt_exn init_stmt_ptr source_range in - instruction - {trans_state with succ_nodes= res_trans_cond_var.control.root_nodes} - init_stmt + instruction {trans_state with succ_nodes= res_trans_cond_var.control.root_nodes} init_stmt | None -> res_trans_cond_var in @@ -2291,9 +2271,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s init_expr_opt = match init_expr_opt with | None -> ( - match - Option.bind qual_type ~f:(fun qt -> CAst_utils.get_type qt.Clang_ast_t.qt_type_ptr) - with + match Option.bind qual_type ~f:(fun qt -> CAst_utils.get_type qt.Clang_ast_t.qt_type_ptr) with | Some (Clang_ast_t.VariableArrayType (_, _, stmt_pointer)) -> (* Set the dynamic length of the variable length array. Variable length array cannot have an initialization expression. *) @@ -2306,16 +2284,13 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s let var_exp, var_typ = var_exp_typ in let context = trans_state.context in let sil_loc = - CLocation.location_of_stmt_info context.translation_unit_context.source_file - var_stmt_info + CLocation.location_of_stmt_info context.translation_unit_context.source_file var_stmt_info in let trans_state_pri = PriorityNode.try_claim_priority_node trans_state var_stmt_info in (* if ie is a block the translation need to be done with the block special cases by exec_with_block_priority *) let res_trans_ie = - let trans_state' = - {trans_state_pri with succ_nodes= []; var_exp_typ= Some var_exp_typ} - in + let trans_state' = {trans_state_pri with succ_nodes= []; var_exp_typ= Some var_exp_typ} in let instruction' = exec_with_glvalue_as_reference instruction in exec_with_block_priority_exception instruction' trans_state' ie var_stmt_info in @@ -2323,15 +2298,15 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s if is_var_unused || (* variable might be initialized already - do nothing in that case*) - List.exists ~f:(Exp.equal var_exp) res_trans_ie.control.initd_exps + List.exists ~f:(Exp.equal var_exp) res_trans_ie.control.initd_exps then None else let sil_e1', ie_typ = res_trans_ie.return in Some { empty_control with instrs= - [ Sil.Store - {e1= var_exp; root_typ= ie_typ; typ= ie_typ; e2= sil_e1'; loc= sil_loc} ] } + [Sil.Store {e1= var_exp; root_typ= ie_typ; typ= ie_typ; e2= sil_e1'; loc= sil_loc}] + } in let pre_init_opt = match var_exp with @@ -2574,7 +2549,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s let procname = Procdesc.get_proc_name procdesc in let trans_state_pri = PriorityNode.try_claim_priority_node trans_state stmt_info in (* Check that the destructor-injecting functions do not create new nodes for return statement - This is ensured by creating a fresh pointer in these functions. *) + This is ensured by creating a fresh pointer in these functions. *) let check_destructor_translation = function | Some {control= {root_nodes}} -> assert (List.is_empty root_nodes) @@ -2599,7 +2574,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s else None in (* `cxx_inject_field_destructors_in_destructor_body` should not create new nodes for return statement, - this is ensured by creating a fresh pointer in `cxx_inject_field_destructors_in_destructor_body` + this is ensured by creating a fresh pointer in `cxx_inject_field_destructors_in_destructor_body` *) check_destructor_translation destructor_res ; let instrs_of = function Some {control= {instrs}} -> instrs | None -> [] in @@ -2625,11 +2600,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s let id = Ident.create_fresh Ident.knormal in let instr = Sil.Load - { id - ; e= Exp.Lvar pvar - ; root_typ= ret_param_typ - ; typ= ret_param_typ - ; loc= sil_loc } + {id; e= Exp.Lvar pvar; root_typ= ret_param_typ; typ= ret_param_typ; loc= sil_loc} in let ret_typ = match ret_param_typ.desc with Typ.Tptr (t, _) -> t | _ -> assert false @@ -2646,8 +2617,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s if List.exists ~f:(Exp.equal ret_exp) res_trans_stmt.control.initd_exps then [] else let sil_expr, _ = res_trans_stmt.return in - [ Sil.Store - {e1= ret_exp; root_typ= ret_type; typ= ret_typ; e2= sil_expr; loc= sil_loc} ] + [Sil.Store {e1= ret_exp; root_typ= ret_type; typ= ret_typ; e2= sil_expr; loc= sil_loc}] in let instrs = var_instrs @ res_trans_stmt.control.instrs @ ret_instrs in let ret_node = mk_ret_node instrs in @@ -2659,8 +2629,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s res_trans_stmt.control.root_nodes else [ret_node] in - mk_trans_result res_trans_stmt.return - {empty_control with root_nodes= root_nodes_to_parent} + mk_trans_result res_trans_stmt.return {empty_control with root_nodes= root_nodes_to_parent} | [] -> (* return; *) let ret_node = mk_ret_node [] in @@ -2685,9 +2654,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s CType_decl.class_from_pointer_type trans_state.context.CContext.tenv info.Clang_ast_t.ei_qual_type in - let obj_c_message_expr_info = - Ast_expressions.make_obj_c_message_expr_info_class sel typ None - in + let obj_c_message_expr_info = Ast_expressions.make_obj_c_message_expr_info_class sel typ None in let message_stmt = Clang_ast_t.ObjCMessageExpr (stmt_info, stmts, info, obj_c_message_expr_info) in @@ -2698,9 +2665,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s let open Clang_ast_t in match CAst_utils.get_decl_opt method_pointer with | Some (ObjCMethodDecl (decl_info, named_decl_info, _)) -> - let typ = - CAst_utils.qual_type_of_decl_ptr (Option.value_exn decl_info.di_parent_pointer) - in + let typ = CAst_utils.qual_type_of_decl_ptr (Option.value_exn decl_info.di_parent_pointer) in let obj_c_mes_expr_info = { Clang_ast_t.omei_selector= named_decl_info.Clang_ast_t.ni_name ; omei_receiver_kind= `Class typ @@ -2743,9 +2708,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s in let meth = CFrontend_config.string_with_utf8_m in let obj_c_mess_expr_info = Ast_expressions.make_obj_c_message_expr_info_class meth typ None in - let message_stmt = - Clang_ast_t.ObjCMessageExpr (stmt_info, stmts, info, obj_c_mess_expr_info) - in + let message_stmt = Clang_ast_t.ObjCMessageExpr (stmt_info, stmts, info, obj_c_mess_expr_info) in instruction trans_state message_stmt @@ -2754,7 +2717,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s __set_locked_attribue(anObj); body; __delete_locked_attribute(anObj); - *) + *) and objCAtSynchronizedStmt_trans trans_state stmt_list stmt_info = match stmt_list with | [lockExpr; compound_stmt] -> @@ -2827,10 +2790,8 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s (trans_results :: trans_results_acc, exp_pvar_typ :: captured_vars_acc) in let translate_captured - { Clang_ast_t.lci_captured_var - ; lci_init_captured_vardecl - ; lci_capture_this - ; lci_capture_kind } ((trans_results_acc, captured_vars_acc) as acc) = + {Clang_ast_t.lci_captured_var; lci_init_captured_vardecl; lci_capture_this; lci_capture_kind} + ((trans_results_acc, captured_vars_acc) as acc) = let is_by_ref = (* see http://en.cppreference.com/w/cpp/language/lambda *) match lci_capture_kind with @@ -2838,8 +2799,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s | `LCK_This (* explicit with [this] or implicit with [&] *) | `LCK_VLAType (* capture a variable-length array by reference. we probably don't handle - this correctly elsewhere, but it's definitely not captured by value! *) - -> + this correctly elsewhere, but it's definitely not captured by value! *) -> true | `LCK_ByCopy (* explicit with [x] or implicit with [=] *) -> (* [=] captures this by reference and everything else by value *) @@ -2932,9 +2892,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s in (* Need a new stmt_info for the translation of the initializer, so that it can create nodes *) (* if it needs to, with the same stmt_info it doesn't work. *) - let init_stmt_info = - {stmt_info with Clang_ast_t.si_pointer= CAst_utils.get_fresh_pointer ()} - in + let init_stmt_info = {stmt_info with Clang_ast_t.si_pointer= CAst_utils.get_fresh_pointer ()} in let res_trans_init = match stmt_opt with | Some (InitListExpr _) -> @@ -3155,8 +3113,8 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s let field_exp = Exp.Lfield (ret_exp, field_name, typ) in let args = type_info_objc :: (field_exp, void_typ) - :: Option.value_map ~default:[] res_trans_subexpr ~f:(fun trans_result -> - [trans_result.return] ) + :: Option.value_map ~default:[] res_trans_subexpr ~f:(fun trans_result -> [trans_result.return] + ) in let call_instr = Sil.Call ((ret_id, typ), sil_fun, args, sil_loc, CallFlags.default) in let res_control = {empty_control with instrs= [call_instr]} in @@ -3189,9 +3147,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s let ret_id = Ident.create_fresh Ident.knormal in let ret_exp = Exp.Var ret_id in let call_instr = Sil.Call ((ret_id, typ), sil_fun, params, sil_loc, CallFlags.default) in - let res_trans_call = - mk_trans_result (ret_exp, typ) {empty_control with instrs= [call_instr]} - in + let res_trans_call = mk_trans_result (ret_exp, typ) {empty_control with instrs= [call_instr]} in let all_res_trans = res_trans_subexpr_list @ [res_trans_call] in PriorityNode.compute_results_to_parent trans_state_pri sil_loc ~node_name:CXXStdInitializerListExpr stmt_info ~return:res_trans_call.return all_res_trans @@ -3327,16 +3283,14 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s logged_error := true ; let {Clang_ast_t.si_source_range}, _ = Clang_ast_proj.get_stmt_tuple instr in let source_file = - trans_state.context.CContext.translation_unit_context - .CFrontend_config.source_file + trans_state.context.CContext.translation_unit_context.CFrontend_config.source_file in let loc_start = CLocation.location_of_source_range ~pick_location:`Start source_file si_source_range in let loc_end = - CLocation.location_of_source_range ~pick_location:`End source_file - si_source_range + CLocation.location_of_source_range ~pick_location:`End source_file si_source_range in (* Unfortunately this triggers regularly so do not show the message on the console unless asked to do so or if the error will crash the frontend. *) @@ -3501,8 +3455,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s memberExpr_trans trans_state stmt_info stmt_list member_expr_info | UnaryOperator (stmt_info, stmt_list, expr_info, unary_operator_info) -> if - is_logical_negation_of_int trans_state.context.CContext.tenv expr_info - unary_operator_info + is_logical_negation_of_int trans_state.context.CContext.tenv expr_info unary_operator_info then let conditional = Ast_expressions.trans_negation_with_conditional stmt_info expr_info stmt_list @@ -3621,8 +3574,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s sub-expressions *) | ObjCAvailabilityCheckExpr (_, _, expr_info, _) -> undefined_expr trans_state expr_info - | SubstNonTypeTemplateParmExpr (_, stmts, _) | SubstNonTypeTemplateParmPackExpr (_, stmts, _) - -> + | SubstNonTypeTemplateParmExpr (_, stmts, _) | SubstNonTypeTemplateParmPackExpr (_, stmts, _) -> let[@warning "-8"] [expr] = stmts in instruction trans_state expr (* Infer somehow ended up in templated non instantiated code - right now @@ -3734,9 +3686,7 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s let (stmt_info, stmts), ret_typ = match Clang_ast_proj.get_expr_tuple instr with | Some (stmt_info, stmts, expr_info) -> - let ret_typ = - CType_decl.get_type_from_expr_info expr_info trans_state.context.tenv - in + let ret_typ = CType_decl.get_type_from_expr_info expr_info trans_state.context.tenv in ((stmt_info, stmts), ret_typ) | None -> let stmt_tuple = Clang_ast_proj.get_stmt_tuple instr in @@ -3805,8 +3755,8 @@ module CTrans_funct (F : CModule_type.CFrontend) : CModule_type.CTranslation = s ( { root_nodes= control_tail_rev.root_nodes ; leaf_nodes= res_trans_s.control.leaf_nodes ; instrs= List.rev_append res_trans_s.control.instrs control_tail_rev.instrs - ; initd_exps= - List.rev_append res_trans_s.control.initd_exps control_tail_rev.initd_exps } + ; initd_exps= List.rev_append res_trans_s.control.initd_exps control_tail_rev.initd_exps + } , res_trans_s.return :: returns_tail_rev ) in let rev_control, rev_returns = diff --git a/infer/src/clang/cTrans_models.ml b/infer/src/clang/cTrans_models.ml index 8236cf40b..a6818c163 100644 --- a/infer/src/clang/cTrans_models.ml +++ b/infer/src/clang/cTrans_models.ml @@ -104,9 +104,8 @@ let get_predefined_ms_is_kind_of_class class_name method_name mk_procname = let name = Mangled.from_string CFrontend_config.self in let params = [CMethodSignature.mk_param_type name class_type] in let bool_type = CType_to_sil_type.type_of_builtin_type_kind `Bool in - get_predefined_ms_method condition class_name method_name - Typ.Procname.ObjC_Cpp.ObjCInstanceMethod mk_procname params (bool_type, Annot.Item.empty) [] - (Some BuiltinDecl.__instanceof) + get_predefined_ms_method condition class_name method_name Typ.Procname.ObjC_Cpp.ObjCInstanceMethod + mk_procname params (bool_type, Annot.Item.empty) [] (Some BuiltinDecl.__instanceof) let get_predefined_model_method_signature class_name method_name mk_procname = diff --git a/infer/src/clang/cTrans_utils.ml b/infer/src/clang/cTrans_utils.ml index 7f3613ff6..ebce84c7c 100644 --- a/infer/src/clang/cTrans_utils.ml +++ b/infer/src/clang/cTrans_utils.ml @@ -35,11 +35,7 @@ module Nodes = struct let is_true_prune_node n = - match Procdesc.Node.get_kind n with - | Procdesc.Node.Prune_node (true, _, _) -> - true - | _ -> - false + match Procdesc.Node.get_kind n with Procdesc.Node.Prune_node (true, _, _) -> true | _ -> false let create_prune_node proc_desc ~branch ~negate_cond e_cond instrs_cond loc if_kind = @@ -258,14 +254,10 @@ module Loops = struct ; increment: Clang_ast_t.stmt ; body: Clang_ast_t.stmt } | While of - { decl_stmt: Clang_ast_t.stmt option - ; condition: Clang_ast_t.stmt - ; body: Clang_ast_t.stmt } + {decl_stmt: Clang_ast_t.stmt option; condition: Clang_ast_t.stmt; body: Clang_ast_t.stmt} | DoWhile of {condition: Clang_ast_t.stmt; body: Clang_ast_t.stmt} - let get_body loop_kind = - match loop_kind with For {body} | While {body} | DoWhile {body} -> body - + let get_body loop_kind = match loop_kind with For {body} | While {body} | DoWhile {body} -> body let get_cond loop_kind = match loop_kind with For {condition} | While {condition} | DoWhile {condition} -> condition @@ -341,9 +333,7 @@ let objc_new_trans trans_state ~alloc_builtin loc stmt_info cls_name function_ty trans_state.context.CContext.cfg pname method_kind None ; let args = [(alloc_ret_exp, alloc_ret_type)] in let ret_id_typ = (init_ret_id, alloc_ret_type) in - let init_stmt_call = - Sil.Call (ret_id_typ, Exp.Const (Const.Cfun pname), args, loc, call_flags) - in + let init_stmt_call = Sil.Call (ret_id_typ, Exp.Const (Const.Cfun pname), args, loc, call_flags) in let instrs = alloc_stmt_call @ [init_stmt_call] in let res_trans_tmp = {empty_control with instrs} in let node_name = Procdesc.Node.CallObjCNew in @@ -568,9 +558,7 @@ let extract_stmt_from_singleton stmt_list source_range warning_string = module Self = struct exception SelfClassException of - { class_name: Typ.Name.t - ; position: Logging.ocaml_pos - ; source_range: Clang_ast_t.source_range } + {class_name: Typ.Name.t; position: Logging.ocaml_pos; source_range: Clang_ast_t.source_range} let add_self_parameter_for_super_instance stmt_info context procname loc mei = if is_superinstance mei then diff --git a/infer/src/clang/cTrans_utils.mli b/infer/src/clang/cTrans_utils.mli index b25a158e6..5cd71349b 100644 --- a/infer/src/clang/cTrans_utils.mli +++ b/infer/src/clang/cTrans_utils.mli @@ -212,9 +212,7 @@ module Loops : sig ; increment: Clang_ast_t.stmt ; body: Clang_ast_t.stmt } | While of - { decl_stmt: Clang_ast_t.stmt option - ; condition: Clang_ast_t.stmt - ; body: Clang_ast_t.stmt } + {decl_stmt: Clang_ast_t.stmt option; condition: Clang_ast_t.stmt; body: Clang_ast_t.stmt} | DoWhile of {condition: Clang_ast_t.stmt; body: Clang_ast_t.stmt} val get_cond : loop_kind -> Clang_ast_t.stmt @@ -227,9 +225,7 @@ end module Self : sig exception SelfClassException of - { class_name: Typ.Name.t - ; position: Logging.ocaml_pos - ; source_range: Clang_ast_t.source_range } + {class_name: Typ.Name.t; position: Logging.ocaml_pos; source_range: Clang_ast_t.source_range} val add_self_parameter_for_super_instance : Clang_ast_t.stmt_info diff --git a/infer/src/clang/cVar_decl.ml b/infer/src/clang/cVar_decl.ml index 0675aed11..33124098b 100644 --- a/infer/src/clang/cVar_decl.ml +++ b/infer/src/clang/cVar_decl.ml @@ -85,13 +85,12 @@ let sil_var_of_captured_var context source_range procname decl_ref = match decl_ref with | {Clang_ast_t.dr_name= Some {Clang_ast_t.ni_name}} -> (* In Objective-C class methods, self is not the standard self instance, since in this - context we don't have an instance. Instead it is used to get the class of the method. - We translate this variables in a different way than normal, we don't treat them as - variables in Sil, instead we remove them and get the class directly in the frontend. - For that reason, we shouldn't add them as captured variables of blocks, since they - don't appear anywhere else in the translation. *) - if is_block_inside_objc_class_method && String.equal ni_name CFrontend_config.self then - None + context we don't have an instance. Instead it is used to get the class of the method. + We translate this variables in a different way than normal, we don't treat them as + variables in Sil, instead we remove them and get the class directly in the frontend. + For that reason, we shouldn't add them as captured variables of blocks, since they + don't appear anywhere else in the translation. *) + if is_block_inside_objc_class_method && String.equal ni_name CFrontend_config.self then None else Some (sil_var_of_decl_ref context source_range decl_ref procname) | _ -> assert false diff --git a/infer/src/concurrency/ConcurrencyModels.ml b/infer/src/concurrency/ConcurrencyModels.ml index eba9782d6..d84d34fc0 100644 --- a/infer/src/concurrency/ConcurrencyModels.ml +++ b/infer/src/concurrency/ConcurrencyModels.ml @@ -85,9 +85,7 @@ end = struct [ { def with classname= "apache::thrift::concurrency::Monitor" ; trylock= "timedlock" :: def.trylock } - ; { def with - classname= "apache::thrift::concurrency::Mutex" - ; trylock= "timedlock" :: def.trylock } + ; {def with classname= "apache::thrift::concurrency::Mutex"; trylock= "timedlock" :: def.trylock} ; {rwm with classname= "apache::thrift::concurrency::NoStarveReadWriteMutex"} ; {rwm with classname= "apache::thrift::concurrency::ReadWriteMutex"} ; {shd with classname= "boost::shared_mutex"} @@ -117,8 +115,7 @@ end = struct let mk_matcher methods = let matcher = QualifiedCppName.Match.of_fuzzy_qual_names methods in - fun pname -> - QualifiedCppName.Match.match_qualifiers matcher (Typ.Procname.get_qualifiers pname) + fun pname -> QualifiedCppName.Match.match_qualifiers matcher (Typ.Procname.get_qualifiers pname) let is_lock, is_unlock, is_trylock, is_std_lock = @@ -341,12 +338,11 @@ let ui_matcher_records = ; {default with classname= "android.app.Application"; methods= ["onCreate"]} ; { default with classname= "android.app.Activity" - ; methods= ["onCreate"; "onStart"; "onRestart"; "onResume"; "onPause"; "onStop"; "onDestroy"] - } + ; methods= ["onCreate"; "onStart"; "onRestart"; "onResume"; "onPause"; "onStop"; "onDestroy"] } ; { default with (* according to Android documentation, *all* methods of the View class run on UI thread, but - let's be a bit conservative and catch all methods that start with "on". - https://developer.android.com/reference/android/view/View.html *) + let's be a bit conservative and catch all methods that start with "on". + https://developer.android.com/reference/android/view/View.html *) method_prefix= true ; classname= "android.view.View" ; methods= ["on"] } ] diff --git a/infer/src/concurrency/ExplicitTrace.mli b/infer/src/concurrency/ExplicitTrace.mli index 7ede52f53..d7988854e 100644 --- a/infer/src/concurrency/ExplicitTrace.mli +++ b/infer/src/concurrency/ExplicitTrace.mli @@ -24,8 +24,8 @@ end module type CallPrinter = PrettyPrintable.PrintableType with type t = CallSite.t -(** Printer which outputs "Method call: " *) module DefaultCallPrinter : CallPrinter +(** Printer which outputs "Method call: " *) module type TraceElem = sig type elem_t @@ -33,8 +33,8 @@ module type TraceElem = sig (** An [elem] which occured at [loc], after the chain of steps (usually calls) in [trace]. *) type t = private {elem: elem_t; loc: Location.t; trace: CallSite.t list} - (** Both [pp] and [describe] simply call the same function on the trace element. *) include Element with type t := t + (** Both [pp] and [describe] simply call the same function on the trace element. *) val make : elem_t -> Location.t -> t @@ -48,8 +48,8 @@ module type TraceElem = sig val with_callsite : t -> CallSite.t -> t (** Push given callsite onto trace, extending the call chain by one. *) - (** A powerset of traces. *) module FiniteSet : FiniteSet with type elt = t + (** A powerset of traces. *) end (* The [compare] function produced ignores traces but *not* locations *) diff --git a/infer/src/concurrency/MethodMatcher.ml b/infer/src/concurrency/MethodMatcher.ml index a558341ab..16c82543a 100644 --- a/infer/src/concurrency/MethodMatcher.ml +++ b/infer/src/concurrency/MethodMatcher.ml @@ -66,8 +66,7 @@ type record = ; methods: string list } let of_record {search_superclasses; method_prefix; actuals_pred; classname; methods} = - call_matches ~search_superclasses ~method_prefix ~actuals_pred classname methods - |> Staged.unstage + call_matches ~search_superclasses ~method_prefix ~actuals_pred classname methods |> Staged.unstage let default = diff --git a/infer/src/concurrency/RacerD.ml b/infer/src/concurrency/RacerD.ml index 4ab5b3476..a86150bc8 100644 --- a/infer/src/concurrency/RacerD.ml +++ b/infer/src/concurrency/RacerD.ml @@ -51,8 +51,8 @@ module TransferFunctions (CFG : ProcCfg.S) = struct add_field_accesses base acc accesses ) - let make_container_access ret_base callee_pname ~is_write receiver_ap callee_loc tenv - caller_pdesc (astate : Domain.t) = + let make_container_access ret_base callee_pname ~is_write receiver_ap callee_loc tenv caller_pdesc + (astate : Domain.t) = let open Domain in let callee_access = if RacerDModels.is_synchronized_container callee_pname receiver_ap tenv then None @@ -282,8 +282,8 @@ module TransferFunctions (CFG : ProcCfg.S) = struct {astate with threads= ThreadsDomain.AnyThreadButSelf} else (* if we don't have any evidence about whether the current function can run in parallel - with other threads or not, start assuming that it can. why use a lock if the function - can't run in a multithreaded context? *) + with other threads or not, start assuming that it can. why use a lock if the function + can't run in a multithreaded context? *) let update_for_lock_use = function | ThreadsDomain.AnyThreadButSelf -> ThreadsDomain.AnyThreadButSelf @@ -372,8 +372,8 @@ module TransferFunctions (CFG : ProcCfg.S) = struct match AccessExpression.get_typ lhs_access_exp tenv with | Some {Typ.desc= Typ.Tint ILong | Tfloat FDouble} -> (* writes to longs and doubles are not guaranteed to be atomic in Java - (http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.7), so there - can be a race even if the RHS is functional *) + (http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.7), so there + can be a race even if the RHS is functional *) false | _ -> true @@ -381,7 +381,7 @@ module TransferFunctions (CFG : ProcCfg.S) = struct let accesses = if is_functional then (* we want to forget about writes to @Functional fields altogether, otherwise we'll - report spurious read/write races *) + report spurious read/write races *) rhs_accesses else add_access loc ~is_write_access:true astate.locks astate.threads astate.ownership proc_data @@ -420,7 +420,7 @@ module TransferFunctions (CFG : ProcCfg.S) = struct |> Option.fold ~init:astate ~f:(fun init bool_value -> let choices = AttributeMapDomain.get_choices access_expr astate.attribute_map in (* prune (prune_exp) can only evaluate to true if the choice is [bool_value]. - add the constraint that the choice must be [bool_value] to the state *) + add the constraint that the choice must be [bool_value] to the state *) List.fold ~f:(add_choice bool_value) ~init choices ) | _ -> astate @@ -474,8 +474,8 @@ let analyze_procedure {Callbacks.exe_env; summary} = runs_on_ui_thread ~attrs_of_pname tenv proc_name || is_thread_confined_method tenv proc_name then ThreadsDomain.AnyThreadButSelf - else if Procdesc.is_java_synchronized proc_desc || is_marked_thread_safe proc_name tenv - then ThreadsDomain.AnyThread + else if Procdesc.is_java_synchronized proc_desc || is_marked_thread_safe proc_name tenv then + ThreadsDomain.AnyThread else ThreadsDomain.NoThread in let add_owned_local acc (var_data : ProcAttributes.var_data) = @@ -485,7 +485,7 @@ let analyze_procedure {Callbacks.exe_env; summary} = in (* Add ownership to local variables. In cpp, stack-allocated local variables cannot be raced on as every thread has its own stack. - More generally, we will never be confident that a race exists on a local/temp. *) + More generally, we will never be confident that a race exists on a local/temp. *) let own_locals = List.fold ~f:add_owned_local (Procdesc.get_locals proc_desc) ~init:OwnershipDomain.empty in @@ -568,8 +568,7 @@ let get_reporting_explanation_java report_kind tenv pname thread = if is_thread_safe_method pname tenv then Some (F.asprintf - "@\n\ - \ Reporting because current method is annotated %a or overrides an annotated method." + "@\n Reporting because current method is annotated %a or overrides an annotated method." MF.pp_monospaced "@ThreadSafe") else match FbThreadSafety.get_fbthreadsafe_class_annot pname tenv with @@ -601,8 +600,8 @@ let get_reporting_explanation_java report_kind tenv pname thread = | _, Some threadsafe_explanation when RacerDDomain.ThreadsDomain.is_any thread -> ( IssueType.thread_safety_violation , F.asprintf - "%s, so we assume that this method can run in parallel with other non-private methods \ - in the class (including itself)." + "%s, so we assume that this method can run in parallel with other non-private methods in \ + the class (including itself)." threadsafe_explanation ) | _, Some threadsafe_explanation -> ( IssueType.thread_safety_violation @@ -816,10 +815,7 @@ end = struct end module Key = struct - type t = - | Location of PathModuloThis.t - | Container of PathModuloThis.t - | Call of Typ.Procname.t + type t = Location of PathModuloThis.t | Container of PathModuloThis.t | Call of Typ.Procname.t [@@deriving compare] let of_access (access : RacerDDomain.Access.t) = @@ -856,7 +852,7 @@ let should_report_on_proc tenv procdesc = match proc_name with | Java java_pname -> (* return true if procedure is at an abstraction boundary or reporting has been explicitly - requested via @ThreadSafe in java *) + requested via @ThreadSafe in java *) RacerDModels.is_thread_safe_method proc_name tenv || Procdesc.get_access procdesc <> PredSymb.Private && (not (Typ.Procname.Java.is_autogen_method java_pname)) @@ -880,8 +876,7 @@ let should_report_on_proc tenv procdesc = false -let should_report_guardedby_violation classname_str ({snapshot; tenv; procname} : reported_access) - = +let should_report_guardedby_violation classname_str ({snapshot; tenv; procname} : reported_access) = let is_uitthread param = match String.lowercase param with | "ui thread" | "ui-thread" | "ui_thread" | "uithread" -> @@ -1020,8 +1015,8 @@ let report_unsafe_accesses ~issue_log classname (aggregated_access_map : ReportM None else (* unprotected write, but not on a method that may run in parallel with itself - (i.e., not a self race). find accesses on a background thread this access might - conflict with and report them *) + (i.e., not a self race). find accesses on a background thread this access might + conflict with and report them *) List.find_map accesses ~f:(fun {snapshot= other_snapshot; threads= other_threads} -> if TraceElem.is_write other_snapshot.access && ThreadsDomain.is_any other_threads then Some other_snapshot.access @@ -1039,7 +1034,7 @@ let report_unsafe_accesses ~issue_log classname (aggregated_access_map : ReportM acc | (Access.Read _ | ContainerRead _) when AccessSnapshot.is_unprotected snapshot -> (* unprotected read. report all writes as conflicts for java. for c++ filter out - unprotected writes *) + unprotected writes *) let is_conflict {snapshot; threads= other_threads} = TraceElem.is_write snapshot.access && @@ -1053,8 +1048,7 @@ let report_unsafe_accesses ~issue_log classname (aggregated_access_map : ReportM make_read_write_race_description ~read_is_sync:false conflict in let report_kind = ReadWriteRace conflict.snapshot.access in - report_thread_safety_violation ~acc ~make_description ~report_kind reported_access - ) + report_thread_safety_violation ~acc ~make_description ~report_kind reported_access ) | Access.Read _ | ContainerRead _ -> (* protected read. report unprotected writes and opposite protected writes as conflicts *) let can_conflict (snapshot1 : AccessSnapshot.t) (snapshot2 : AccessSnapshot.t) = @@ -1073,8 +1067,7 @@ let report_unsafe_accesses ~issue_log classname (aggregated_access_map : ReportM make_read_write_race_description ~read_is_sync:true conflict in let report_kind = ReadWriteRace conflict.snapshot.access in - report_thread_safety_violation ~acc ~make_description ~report_kind reported_access - ) + report_thread_safety_violation ~acc ~make_description ~report_kind reported_access ) in let report_accesses_on_location reportable_accesses init = (* Don't report on location if all accesses are on non-concurrent contexts *) @@ -1096,9 +1089,7 @@ let report_unsafe_accesses ~issue_log classname (aggregated_access_map : ReportM let report grouped_accesses (reported, issue_log) = (* reset the reported reads and writes for each memory location *) let reported = - { reported with - reported_writes= Typ.Procname.Set.empty - ; reported_reads= Typ.Procname.Set.empty } + {reported with reported_writes= Typ.Procname.Set.empty; reported_reads= Typ.Procname.Set.empty} in report_guardedby_violations_on_location grouped_accesses (reported, issue_log) |> report_accesses_on_location grouped_accesses diff --git a/infer/src/concurrency/RacerDDomain.ml b/infer/src/concurrency/RacerDDomain.ml index 54be60197..b8b27773f 100644 --- a/infer/src/concurrency/RacerDDomain.ml +++ b/infer/src/concurrency/RacerDDomain.ml @@ -118,10 +118,10 @@ module CallPrinter = struct end module TraceElem = struct + include ExplicitTrace.MakeTraceElemModuloLocation (Access) (CallPrinter) (** This choice means the comparator is insensitive to the location access. This preserves correctness only if the overlying comparator (AccessSnapshot) takes into account the characteristics of the access (eg lock status). *) - include ExplicitTrace.MakeTraceElemModuloLocation (Access) (CallPrinter) let is_write {elem} = Access.is_write elem @@ -569,8 +569,8 @@ let empty_summary = let pp_summary fmt {threads; locks; accesses; return_ownership; return_attributes} = F.fprintf fmt "@\nThreads: %a, Locks: %a @\nAccesses %a @\nOwnership: %a @\nReturn Attributes: %a @\n" - ThreadsDomain.pp threads LocksDomain.pp locks AccessDomain.pp accesses - OwnershipAbstractValue.pp return_ownership AttributeSetDomain.pp return_attributes + ThreadsDomain.pp threads LocksDomain.pp locks AccessDomain.pp accesses OwnershipAbstractValue.pp + return_ownership AttributeSetDomain.pp return_attributes let pp fmt {threads; locks; accesses; ownership; attribute_map} = diff --git a/infer/src/concurrency/RacerDModels.ml b/infer/src/concurrency/RacerDModels.ml index 9925e0ad3..779eb796f 100644 --- a/infer/src/concurrency/RacerDModels.ml +++ b/infer/src/concurrency/RacerDModels.ml @@ -119,8 +119,8 @@ let get_container_access pn tenv = | Typ.Procname.Java _ -> None (* The following order matters: we want to check if pname is a container write - before we check if pname is a container read. This is due to a different - treatment between std::map::operator[] and all other operator[]. *) + before we check if pname is a container read. This is due to a different + treatment between std::map::operator[] and all other operator[]. *) | (Typ.Procname.ObjC_Cpp _ | C _) when is_cpp_container_write pn -> Some ContainerWrite | (Typ.Procname.ObjC_Cpp _ | C _) when is_cpp_container_read pn -> @@ -167,7 +167,7 @@ let is_functional pname = with | "android.content.res.Resources", method_name -> (* all methods of Resources are considered @Functional except for the ones in this - blacklist *) + blacklist *) let non_functional_resource_methods = [ "getAssets" ; "getConfiguration" @@ -282,8 +282,8 @@ let is_thread_safe item_annot = let f ((annot : Annot.t), _) = List.exists ~f:(fun annot_string -> - Annotations.annot_ends_with annot annot_string - || String.equal annot.class_name annot_string ) + Annotations.annot_ends_with annot annot_string || String.equal annot.class_name annot_string + ) threadsafe_annotations && match annot.Annot.parameters with @@ -405,7 +405,7 @@ let should_flag_interface_call tenv exps call_flags pname = && (not (is_java_library java_pname)) && (not (is_builder_function java_pname)) (* can't ask anyone to annotate interfaces in library code, and Builders should always be - thread-safe (would be unreasonable to ask everyone to annotate them) *) + thread-safe (would be unreasonable to ask everyone to annotate them) *) && ConcurrencyModels.find_override_or_superclass_annotated ~attrs_of_pname thread_safe_or_thread_confined tenv pname |> Option.is_none diff --git a/infer/src/concurrency/StarvationModels.ml b/infer/src/concurrency/StarvationModels.ml index 445f5251e..1e0653cbf 100644 --- a/infer/src/concurrency/StarvationModels.ml +++ b/infer/src/concurrency/StarvationModels.ml @@ -75,8 +75,8 @@ let empty_or_excessive_timeout actuals = |> Option.value_map ~default:false ~f:(fun duration -> is_excessive_secs (0.001 *. duration)) | [_; snd_arg; third_arg] -> (* this is either a call to Object.wait(_, _) or to a java.util.concurent.lock(_, _) method. - In the first case the arguments are a duration in milliseconds and an extra duration in - nanoseconds; in the second case, the arguments are a duration and a time unit. *) + In the first case the arguments are a duration in milliseconds and an extra duration in + nanoseconds; in the second case, the arguments are a duration and a time unit. *) duration_of_exp snd_arg |> Option.value_map ~default:false ~f:(fun duration -> match timeunit_of_exp third_arg with diff --git a/infer/src/concurrency/starvation.ml b/infer/src/concurrency/starvation.ml index 4dcaade21..328f4f837 100644 --- a/infer/src/concurrency/starvation.ml +++ b/infer/src/concurrency/starvation.ml @@ -381,7 +381,7 @@ let should_report_deadlock_on_current_proc current_elem endpoint_elem = c < 0 || Int.equal 0 c && (* same class, so choose depending on location *) - Location.compare current_elem.CriticalPair.loc endpoint_elem.CriticalPair.loc < 0 + Location.compare current_elem.CriticalPair.loc endpoint_elem.CriticalPair.loc < 0 let should_report pdesc = @@ -508,7 +508,7 @@ let report_on_pair ((tenv, summary) as env) (pair : Domain.CriticalPair.t) repor |> Option.value_map ~default:report_map ~f:(fun other_class -> (* get the class of the root variable of the lock in the lock acquisition and retrieve all the summaries of the methods of that class; - then, report on the parallel composition of the current pair and any pair in these + then, report on the parallel composition of the current pair and any pair in these summaries that can indeed run in parallel *) fold_reportable_summaries env other_class ~init:report_map ~f:(fun acc (other_pname, {critical_pairs}) -> diff --git a/infer/src/concurrency/starvationDomain.ml b/infer/src/concurrency/starvationDomain.ml index 11cc6eaf1..7e7178df3 100644 --- a/infer/src/concurrency/starvationDomain.ml +++ b/infer/src/concurrency/starvationDomain.ml @@ -55,7 +55,7 @@ module ThreadDomain = struct let is_uithread = function UIThread -> true | _ -> false - (* If we know that either the caller is a UI/BG thread or both, keep it that way. + (* If we know that either the caller is a UI/BG thread or both, keep it that way. Otherwise, we have no info on caller, so use callee's info. *) let integrate_summary ~caller ~callee = if is_bottom caller then callee else caller @@ -100,11 +100,7 @@ module Lock = struct let pp = AccessPath.pp let owner_class ((_, {Typ.desc}), _) = - match desc with - | Typ.Tstruct name | Typ.Tptr ({desc= Tstruct name}, _) -> - Some name - | _ -> - None + match desc with Typ.Tstruct name | Typ.Tptr ({desc= Tstruct name}, _) -> Some name | _ -> None let describe fmt lock = @@ -206,7 +202,7 @@ end = struct module Map = AbstractDomain.InvertedMap (Lock) (LockCount) - (* [acquisitions] has the currently held locks, so as to avoid a linear fold in [get_acquisitions]. + (* [acquisitions] has the currently held locks, so as to avoid a linear fold in [get_acquisitions]. This should also increase sharing across returned values from [get_acquisitions]. *) type t = {map: Map.t; acquisitions: Acquisitions.t} @@ -338,8 +334,7 @@ module CriticalPair = struct Acquisitions.fold (fun {procname= acq_procname; loc= acq_loc} acc -> if - Typ.Procname.equal procname acq_procname - && Int.is_negative (Location.compare acq_loc acc) + Typ.Procname.equal procname acq_procname && Int.is_negative (Location.compare acq_loc acc) then acq_loc else acc ) acquisitions initial_loc @@ -368,7 +363,7 @@ module CriticalPair = struct let trace = Typ.Procname.Map.find_opt procname acquisitions_map |> Option.value ~default:[] - (* many acquisitions can be on same line (eg, std::lock) so use stable sort + (* many acquisitions can be on same line (eg, std::lock) so use stable sort to produce a deterministic trace *) |> List.stable_sort ~compare:Acquisition.compare_loc |> List.map ~f:Acquisition.make_trace_step @@ -552,15 +547,14 @@ let acquire tenv ({lock_state; critical_pairs} as astate) ~procname ~loc locks = let event = Event.make_acquire lock in add_critical_pair (Some tenv) lock_state event astate.thread ~loc acc ) ; lock_state= - List.fold locks ~init:lock_state ~f:(fun acc lock -> - LockState.acquire ~procname ~loc lock acc ) } + List.fold locks ~init:lock_state ~f:(fun acc lock -> LockState.acquire ~procname ~loc lock acc) + } let make_call_with_event new_event ~loc astate = { astate with critical_pairs= - add_critical_pair None astate.lock_state new_event astate.thread ~loc astate.critical_pairs - } + add_critical_pair None astate.lock_state new_event astate.thread ~loc astate.critical_pairs } let blocking_call ~callee sev ~loc astate = @@ -630,8 +624,7 @@ let pp_summary fmt (summary : summary) = let integrate_summary tenv callsite (astate : t) (summary : summary) = let critical_pairs' = - CriticalPairs.with_callsite summary.critical_pairs tenv astate.lock_state callsite - astate.thread + CriticalPairs.with_callsite summary.critical_pairs tenv astate.lock_state callsite astate.thread in { astate with critical_pairs= CriticalPairs.join astate.critical_pairs critical_pairs' diff --git a/infer/src/concurrency/starvationDomain.mli b/infer/src/concurrency/starvationDomain.mli index 714fc29de..3fe224412 100644 --- a/infer/src/concurrency/starvationDomain.mli +++ b/infer/src/concurrency/starvationDomain.mli @@ -106,8 +106,8 @@ end module BranchGuardDomain : sig include AbstractDomain.InvertedMapS - with type key = HilExp.AccessExpression.t - and type value = BranchGuard.t + with type key = HilExp.AccessExpression.t + and type value = BranchGuard.t val is_thread_guard : HilExp.AccessExpression.t -> t -> bool end diff --git a/infer/src/dune.in b/infer/src/dune.in index d1c5f84ff..b1c9e3928 100644 --- a/infer/src/dune.in +++ b/infer/src/dune.in @@ -32,9 +32,7 @@ let source_dirs = ; "unit" ^/ "nullsafe" ] ) -let infer_binaries = - ["infer"; "inferunit"] @ if facebook then ["InferCreateTraceViewLinks"] else [] - +let infer_binaries = ["infer"; "inferunit"] @ if facebook then ["InferCreateTraceViewLinks"] else [] let infer_cflags = common_cflags @@ -110,7 +108,7 @@ let stanzas = (fun source_dir -> [ Printf.sprintf "(copy_files# %s/*.ml{,i,l})" source_dir ; (* menhir doesn't support '# 1 ""' directives at the start of the file inserted by - copy# actions *) + copy# actions *) Printf.sprintf "(copy_files %s/*.mly)" source_dir ] ) source_dirs |> List.concat ) diff --git a/infer/src/infer.ml b/infer/src/infer.ml index e49ae3965..ac32988b2 100644 --- a/infer/src/infer.ml +++ b/infer/src/infer.ml @@ -44,8 +44,8 @@ let setup () = if Config.( (* In Buck mode, delete infer-out directories inside buck-out to start fresh and to - avoid getting errors because some of their contents is missing (removed by - [Driver.clean_results_dir ()]). *) + avoid getting errors because some of their contents is missing (removed by + [Driver.clean_results_dir ()]). *) (buck && flavors) || genrule_mode) || not ( Driver.(equal_mode driver_mode Analyze) @@ -64,7 +64,7 @@ let setup () = ResultsDir.assert_results_dir "have you run infer before?" ) ; db_start () ; NullsafeInit.init () ; - if CLOpt.is_originator then ( RunState.add_run_to_sequence () ; RunState.store () ) ; + if CLOpt.is_originator then (RunState.add_run_to_sequence () ; RunState.store ()) ; () diff --git a/infer/src/integration/CaptureCompilationDatabase.ml b/infer/src/integration/CaptureCompilationDatabase.ml index 459dc2937..aacae47f5 100644 --- a/infer/src/integration/CaptureCompilationDatabase.ml +++ b/infer/src/integration/CaptureCompilationDatabase.ml @@ -30,8 +30,7 @@ let invoke_cmd (source_file, (cmd : CompilationDatabase.compilation_data)) = | pid -> !ProcessPoolState.update_status (Mtime_clock.now ()) (SourceFile.to_string source_file) ; Unix.waitpid (Pid.of_int pid) - |> Result.map_error ~f:(fun unix_error -> - Unix.Exit_or_signal.to_string_hum (Error unix_error) ) + |> Result.map_error ~f:(fun unix_error -> Unix.Exit_or_signal.to_string_hum (Error unix_error)) | exception Unix.Unix_error (err, f, arg) -> Error (F.asprintf "%s(%s): %s@." f arg (Unix.Error.message err)) ) |> function @@ -83,8 +82,8 @@ let get_compilation_database_files_buck ~prog ~args = let build_args = (command :: List.rev_append rev_not_targets (List.rev Config.buck_build_args_no_inline)) @ (* Infer doesn't support C++ modules nor precompiled headers yet (T35656509) *) - "--config" :: "*//cxx.pch_enabled=false" :: "--config" :: "*//cxx.modules_default=false" - :: "--config" :: "*//cxx.modules=False" :: targets_args + "--config" :: "*//cxx.pch_enabled=false" :: "--config" :: "*//cxx.modules_default=false" + :: "--config" :: "*//cxx.modules=False" :: targets_args in Logging.(debug Linters Quiet) "Processed buck command is: 'buck %a'@\n" (Pp.seq F.pp_print_string) build_args ; diff --git a/infer/src/integration/CaptureCompilationDatabase.mli b/infer/src/integration/CaptureCompilationDatabase.mli index 849965cc6..57f27b54b 100644 --- a/infer/src/integration/CaptureCompilationDatabase.mli +++ b/infer/src/integration/CaptureCompilationDatabase.mli @@ -14,8 +14,7 @@ val capture_files_in_database : val capture_file_in_database : CompilationDatabase.t -> SourceFile.t -> unit -val get_compilation_database_files_buck : - prog:string -> args:string list -> [> `Raw of string] list +val get_compilation_database_files_buck : prog:string -> args:string list -> [> `Raw of string] list (** Get the compilation database files that contain the compilation given by the buck command. It will be the compilation of the passed targets only or also the dependencies according to the flag --buck-compilation-database deps | no-deps *) diff --git a/infer/src/integration/CompilationDatabase.ml b/infer/src/integration/CompilationDatabase.ml index 0ecc3635f..9e05f1d93 100644 --- a/infer/src/integration/CompilationDatabase.ml +++ b/infer/src/integration/CompilationDatabase.ml @@ -69,8 +69,7 @@ let decode_json_file (database : t) json_format = (* prefer "arguments" when available *) if Option.is_none !command then command := Some (parse_command_and_arguments cmd) | "command", json -> - exit_format_error - "the value of the \"command\" field is not a string; found '%s' instead" + exit_format_error "the value of the \"command\" field is not a string; found '%s' instead" (Yojson.Basic.to_string json) | "arguments", `List args -> ( let args = @@ -90,8 +89,7 @@ let decode_json_file (database : t) json_format = | cmd :: args -> command := Some (cmd, List.map ~f:Escape.escape_shell args) ) | "arguments", json -> - exit_format_error - "the value of the \"arguments\" field is not a list; found '%s' instead" + exit_format_error "the value of the \"arguments\" field is not a list; found '%s' instead" (Yojson.Basic.to_string json) | "output", _ -> () diff --git a/infer/src/integration/Driver.ml b/infer/src/integration/Driver.ml index d4f404f2d..541bc1c03 100644 --- a/infer/src/integration/Driver.ml +++ b/infer/src/integration/Driver.ml @@ -37,8 +37,7 @@ let pp_mode fmt = function | BuckGenruleMaster build_cmd -> F.fprintf fmt "BuckGenrule driver mode:@\nbuild command = %a" Pp.cli_args build_cmd | BuckCompilationDB (prog, args) -> - F.fprintf fmt "BuckCompilationDB driver mode:@\nprog = '%s'@\nargs = %a" prog Pp.cli_args - args + F.fprintf fmt "BuckCompilationDB driver mode:@\nprog = '%s'@\nargs = %a" prog Pp.cli_args args | ClangCompilationDB _ -> F.fprintf fmt "ClangCompilationDB driver mode" | PythonCapture (bs, args) -> @@ -231,11 +230,7 @@ let python_capture build_system build_cmd = [] | Some tool -> ["--force-integration"; Config.string_of_build_system tool] ) - @ ( match Config.java_jar_compiler with - | None -> - [] - | Some p -> - ["--java-jar-compiler"; p] ) + @ (match Config.java_jar_compiler with None -> [] | Some p -> ["--java-jar-compiler"; p]) @ ( match List.rev Config.buck_build_args with | args when in_buck_mode -> List.map ~f:(fun arg -> ["--Xbuck"; "'" ^ arg ^ "'"]) args |> List.concat @@ -259,7 +254,7 @@ let python_capture build_system build_cmd = @ (if not Config.buck_merge_all_deps then [] else ["--buck-merge-all-deps"]) @ ("--" :: updated_build_cmd) ) in - if in_buck_mode && Config.flavors then ( RunState.set_merge_capture true ; RunState.store () ) ; + if in_buck_mode && Config.flavors then (RunState.set_merge_capture true ; RunState.store ()) ; run_command ~prog:infer_py ~args ~cleanup:(function | Error (`Exit_non_zero exit_code) @@ -484,8 +479,8 @@ let assert_supported_build_system build_system = else ( if Config.reactive_mode then L.user_error - "WARNING: The reactive analysis mode is not compatible with the Buck integration \ - for Java" ; + "WARNING: The reactive analysis mode is not compatible with the Buck integration for \ + Java" ; (`Java, Config.string_of_build_system build_system) ) in assert_supported_mode analyzer build_string @@ -563,9 +558,9 @@ let run_prologue mode = if CLOpt.is_originator then ( if Config.dump_duplicate_symbols then reset_duplicates_file () ; (* infer might be called from a Makefile and itself uses `make` to run the analysis in parallel, - but cannot communicate with the parent make command. Since infer won't interfere with them - anyway, pretend that we are not called from another make to prevent make falling back to a - mono-threaded execution. *) + but cannot communicate with the parent make command. Since infer won't interfere with them + anyway, pretend that we are not called from another make to prevent make falling back to a + mono-threaded execution. *) Unix.unsetenv "MAKEFLAGS" ; (* disable the Buck daemon as changes in the Buck or infer config may be missed otherwise *) Unix.putenv ~key:"NO_BUCKD" ~data:"1" ) ; diff --git a/infer/src/integration/Maven.ml b/infer/src/integration/Maven.ml index 91b43a501..baac906dc 100644 --- a/infer/src/integration/Maven.ml +++ b/infer/src/integration/Maven.ml @@ -73,7 +73,7 @@ let add_infer_profile_to_xml dir maven_xml infer_xml = insert_infer_profile xml_out | [_] when not !found_profiles_tag -> (* closing the root tag but no tag found, add - [infer profile] *) + [infer profile] *) Xmlm.output xml_out (`El_start (("", "profiles"), [])) ; found_profiles_tag := true ; (* do not add again *) diff --git a/infer/src/istd/ARList.mli b/infer/src/istd/ARList.mli index aaafc0575..6e9e4000f 100644 --- a/infer/src/istd/ARList.mli +++ b/infer/src/istd/ARList.mli @@ -11,56 +11,56 @@ open! IStd Lists with O(1) append and rev. *) -include - sig - (* ocaml ignores the warning suppression at toplevel, hence the [include struct ... end] trick *) +include sig + (* ocaml ignores the warning suppression at toplevel, hence the [include struct ... end] trick *) - type +'a t + type +'a t - (* O(1) time and O(1) allocation *) + (* O(1) time and O(1) allocation *) - val empty : 'a t + val empty : 'a t - val singleton : 'a -> 'a t + val singleton : 'a -> 'a t - val of_list : 'a list -> 'a t + val of_list : 'a list -> 'a t - val cons : 'a -> 'a t -> 'a t + val cons : 'a -> 'a t -> 'a t - val snoc : 'a t -> 'a -> 'a t + val snoc : 'a t -> 'a -> 'a t - val append : 'a t -> 'a t -> 'a t + val append : 'a t -> 'a t -> 'a t - val rev : 'a t -> 'a t + val rev : 'a t -> 'a t - val is_empty : 'a t -> bool + val is_empty : 'a t -> bool - val is_singleton : 'a t -> 'a option + val is_singleton : 'a t -> 'a option - val is_singleton_or_more : 'a t -> 'a IContainer.singleton_or_more + val is_singleton_or_more : 'a t -> 'a IContainer.singleton_or_more - (* O(1) best to O(N) worst time and allocation. Do not use in a loop, use [fold] instead. *) + (* O(1) best to O(N) worst time and allocation. Do not use in a loop, use [fold] instead. *) - val hd_tl_exn : 'a t -> 'a * 'a t + val hd_tl_exn : 'a t -> 'a * 'a t - val front_last_exn : 'a t -> 'a t * 'a + val front_last_exn : 'a t -> 'a t * 'a - (* O(1) best to O(N) worst time, no allocation *) + (* O(1) best to O(N) worst time, no allocation *) - val hd_exn : 'a t -> 'a + val hd_exn : 'a t -> 'a - val last_exn : 'a t -> 'a + val last_exn : 'a t -> 'a - val hd : 'a t -> 'a option + val hd : 'a t -> 'a option - val last : 'a t -> 'a option + val last : 'a t -> 'a option - (* Theta(N) time, 0 best to Theta(N) worst allocation *) + (* Theta(N) time, 0 best to Theta(N) worst allocation *) - val fold_left : ('a t, 'a, 'accum) Container.fold + val fold_left : ('a t, 'a, 'accum) Container.fold - val fold_right : ('a t, 'a, 'accum) Container.fold + val fold_right : ('a t, 'a, 'accum) Container.fold - val fold_unordered : ('a t, 'a, 'accum) Container.fold - (** Always better than [fold_left] when you do not care about the order. *) -end[@@warning "-32"] + val fold_unordered : ('a t, 'a, 'accum) Container.fold + (** Always better than [fold_left] when you do not care about the order. *) +end +[@@warning "-32"] diff --git a/infer/src/istd/Escape.ml b/infer/src/istd/Escape.ml index e3dfe342d..b0a38e580 100644 --- a/infer/src/istd/Escape.ml +++ b/infer/src/istd/Escape.ml @@ -150,5 +150,5 @@ let escape_shell = escape_double_quotes arg |> F.sprintf "\"%s\"" else (* ends on-going single quote, output single quote inside double quotes, then open a new - single quote *) + single quote *) escape_map (function '\'' -> Some "'\"'\"'" | _ -> None) arg |> F.sprintf "'%s'" diff --git a/infer/src/istd/GOption.ml b/infer/src/istd/GOption.ml index c185ab223..416bc620b 100644 --- a/infer/src/istd/GOption.ml +++ b/infer/src/istd/GOption.ml @@ -13,5 +13,4 @@ type (_, _) t = GNone : (none, _) t | GSome : 'a -> (some, 'a) t let value : (some, 'a) t -> 'a = function GSome v -> v -let value_map (type h) (t : (h, _) t) ~default ~f = - match t with GNone -> default | GSome v -> f v +let value_map (type h) (t : (h, _) t) ~default ~f = match t with GNone -> default | GSome v -> f v diff --git a/infer/src/istd/IContainer.mli b/infer/src/istd/IContainer.mli index c9d2dfd92..c044ff177 100644 --- a/infer/src/istd/IContainer.mli +++ b/infer/src/istd/IContainer.mli @@ -33,8 +33,7 @@ val rev_map_to_list : fold:('t, 'a, 'b list) Container.fold -> 't -> f:('a -> 'b val rev_filter_map_to_list : fold:('t, 'a, 'b list) Container.fold -> 't -> f:('a -> 'b option) -> 'b list -val iter_consecutive : - fold:('t, 'a, 'a option) Container.fold -> 't -> f:('a -> 'a -> unit) -> unit +val iter_consecutive : fold:('t, 'a, 'a option) Container.fold -> 't -> f:('a -> 'a -> unit) -> unit val pp_collection : fold:('t, 'a, 'a option) Container.fold diff --git a/infer/src/istd/IStd.ml b/infer/src/istd/IStd.ml index f4522178d..27e7544c3 100644 --- a/infer/src/istd/IStd.ml +++ b/infer/src/istd/IStd.ml @@ -39,13 +39,9 @@ module ANSITerminal : module type of ANSITerminal = struct (* more careful about when the channel is connected to a tty *) - let print_string = - if Unix.(isatty stdout) then print_string else fun _ -> Pervasives.print_string - - - let prerr_string = - if Unix.(isatty stderr) then prerr_string else fun _ -> Pervasives.prerr_string + let print_string = if Unix.(isatty stdout) then print_string else fun _ -> Pervasives.print_string + let prerr_string = if Unix.(isatty stderr) then prerr_string else fun _ -> Pervasives.prerr_string let printf styles fmt = Format.ksprintf (fun s -> print_string styles s) fmt diff --git a/infer/src/istd/ImperativeUnionFind.ml b/infer/src/istd/ImperativeUnionFind.ml index 5c8e0319f..3a8f3e015 100644 --- a/infer/src/istd/ImperativeUnionFind.ml +++ b/infer/src/istd/ImperativeUnionFind.ml @@ -31,7 +31,7 @@ module Make (Set : Set) = struct module Repr : sig (* Sort-of abstracting away the fact that a representative is just an element itself. - This ensures that the [Sets] hashtable is accessed with representative only. *) + This ensures that the [Sets] hashtable is accessed with representative only. *) type t = private Set.elt diff --git a/infer/src/istd/MaximumSharing.ml b/infer/src/istd/MaximumSharing.ml index e258bac74..a6a57c0cc 100644 --- a/infer/src/istd/MaximumSharing.ml +++ b/infer/src/istd/MaximumSharing.ml @@ -65,8 +65,7 @@ end = struct let hash ((h, _) : t) = (h :> int) let equal ((h1, o1) : t) ((h2, o2) : t) = Int.equal (h1 :> int) (h2 :> int) && eq o1 o2 - end - : Caml.Hashtbl.HashedType + end : Caml.Hashtbl.HashedType with type t = Hashing.hash_value * Obj.t ) @@ -112,7 +111,7 @@ end = struct Obj.repr (lazy (assert false)) - (* + (* TODO: be much more efficient and write it in C to be able to use the GC flags to mark visited values. *) @@ -276,8 +275,8 @@ module ForHashtbl (H : Caml.Hashtbl.S) = struct let normalize h = let sharer = Sharer.create () in (* If a hash table has been created with [add] and not [replace] only, it is possible to - have several values for a given key. We need to collect them all and reinsert them in - the reverse order. *) + have several values for a given key. We need to collect them all and reinsert them in + the reverse order. *) let rev_bindings = H.fold (fun k v acc -> (k, v) :: acc) h [] in (* No need to preserve the initial size of the original hash table *) let h' = H.create (H.length h) in diff --git a/infer/src/istd/StatisticsToolbox.ml b/infer/src/istd/StatisticsToolbox.ml index 689a16563..9d2315bc7 100644 --- a/infer/src/istd/StatisticsToolbox.ml +++ b/infer/src/istd/StatisticsToolbox.ml @@ -7,14 +7,7 @@ open! IStd type t = - { sum: float - ; avg: float - ; min: float - ; p10: float - ; median: float - ; p75: float - ; max: float - ; count: int } + {sum: float; avg: float; min: float; p10: float; median: float; p75: float; max: float; count: int} let to_json s = `Assoc diff --git a/infer/src/java/JProcname.ml b/infer/src/java/JProcname.ml index 802791fc7..6002d9bdf 100644 --- a/infer/src/java/JProcname.ml +++ b/infer/src/java/JProcname.ml @@ -174,9 +174,7 @@ module JNI = struct reduce_aux ~symbols:tl ~unchanged_symbols ~in_method ~jnis_in_method ~jnis:(t :: jnis) | NonTerminal (SymMethod method_jnis) :: Terminal t :: tl -> let transformed_symbols = Terminal (Method (method_jnis, t)) :: tl in - let new_symbols = - List.rev_append (all_collected_symbols_so_far ()) transformed_symbols - in + let new_symbols = List.rev_append (all_collected_symbols_so_far ()) transformed_symbols in reduce_aux ~symbols:new_symbols ~unchanged_symbols:[] ~in_method:false ~jnis_in_method:[] ~jnis | (NonTerminal SymMethodOpen as nt) :: tl -> @@ -185,9 +183,7 @@ module JNI = struct ~in_method:true ~jnis_in_method:[] ~jnis | NonTerminal SymArray :: Terminal t :: tl -> let transformed_symbols = Terminal (Array t) :: tl in - let new_symbols = - List.rev_append (all_collected_symbols_so_far ()) transformed_symbols - in + let new_symbols = List.rev_append (all_collected_symbols_so_far ()) transformed_symbols in reduce_aux ~symbols:new_symbols ~unchanged_symbols:[] ~in_method:false ~jnis_in_method:[] ~jnis | (NonTerminal SymArray as nt) :: tl -> diff --git a/infer/src/java/jClasspath.ml b/infer/src/java/jClasspath.ml index 6fa44b4f7..7598583a9 100644 --- a/infer/src/java/jClasspath.ml +++ b/infer/src/java/jClasspath.ml @@ -257,9 +257,7 @@ let add_class cn jclass program = program.classmap <- JBasics.ClassMap.add cn jclass program.classmap -let set_callee_translated program pname = - Typ.Procname.Hash.replace program.callees pname Translated - +let set_callee_translated program pname = Typ.Procname.Hash.replace program.callees pname Translated let add_missing_callee program pname cn ms = if not (Typ.Procname.Hash.mem program.callees pname) then diff --git a/infer/src/java/jContext.mli b/infer/src/java/jContext.mli index d6eaa4162..033e168c4 100644 --- a/infer/src/java/jContext.mli +++ b/infer/src/java/jContext.mli @@ -13,9 +13,9 @@ open Sawja_pack (** data structure for representing whether an instruction is a goto, a return or a standard instruction. *) type jump_kind = Next | Jump of int | Exit +module NodeTbl : Caml.Hashtbl.S with type key = Procdesc.Node.t (** Hastable for storing nodes that correspond to if-instructions. These are used when adding the edges in the contrl flow graph. *) -module NodeTbl : Caml.Hashtbl.S with type key = Procdesc.Node.t (** data structure for saving the three structures tht contain the intermediate representation of a file: the type environment, the control graph and the control diff --git a/infer/src/java/jMain.ml b/infer/src/java/jMain.ml index 17bdce858..0fe6131a4 100644 --- a/infer/src/java/jMain.ml +++ b/infer/src/java/jMain.ml @@ -123,9 +123,7 @@ let do_all_files classpath sources classes = (* loads the source files and translates them *) let main load_sources_and_classes = - ( match - (Config.biabduction_models_mode, Sys.file_exists Config.biabduction_models_jar = `Yes) - with + ( match (Config.biabduction_models_mode, Sys.file_exists Config.biabduction_models_jar = `Yes) with | true, false -> () | false, false -> diff --git a/infer/src/java/jTrans.ml b/infer/src/java/jTrans.ml index 46627fd40..11767b191 100644 --- a/infer/src/java/jTrans.ml +++ b/infer/src/java/jTrans.ml @@ -945,9 +945,7 @@ let instruction (context : JContext.t) pc instr : translation = let sil_test_true = Exp.UnOp (Unop.LNot, sil_test_false, None) in let sil_instrs_true = Sil.Prune (sil_test_true, loc, true, Sil.Ik_if) in let sil_instrs_false = Sil.Prune (sil_test_false, loc, false, Sil.Ik_if) in - let node_kind_true = - Procdesc.Node.Prune_node (true, Sil.Ik_if, PruneNodeKind_MethodBody) - in + let node_kind_true = Procdesc.Node.Prune_node (true, Sil.Ik_if, PruneNodeKind_MethodBody) in let node_kind_false = Procdesc.Node.Prune_node (false, Sil.Ik_if, PruneNodeKind_MethodBody) in @@ -975,8 +973,7 @@ let instruction (context : JContext.t) pc instr : translation = let class_type = JTransType.get_class_type program tenv cn in let class_type_np = JTransType.get_class_type_no_pointer program tenv cn in let sizeof_exp = - Exp.Sizeof - {typ= class_type_np; nbytes= None; dynamic_length= None; subtype= Subtype.exact} + Exp.Sizeof {typ= class_type_np; nbytes= None; dynamic_length= None; subtype= Subtype.exact} in let args = [(sizeof_exp, class_type)] in let ret_id = Ident.create_fresh Ident.knormal in @@ -1011,11 +1008,7 @@ let instruction (context : JContext.t) pc instr : translation = in let set_instr = Sil.Store - { e1= Exp.Lvar array_name - ; root_typ= array_type - ; typ= array_type - ; e2= Exp.Var ret_id - ; loc } + {e1= Exp.Lvar array_name; root_typ= array_type; typ= array_type; e2= Exp.Var ret_id; loc} in let node_kind = Procdesc.Node.Stmt_node MethodBody in let node = create_node node_kind (instrs @ [call_instr; set_instr]) in @@ -1088,8 +1081,7 @@ let instruction (context : JContext.t) pc instr : translation = let call_node = create_node node_kind (instrs @ call_instrs) in Instr call_node | MonitorEnter expr -> - trans_monitor_enter_exit context expr pc loc BuiltinDecl.__set_locked_attribute - MonitorEnter + trans_monitor_enter_exit context expr pc loc BuiltinDecl.__set_locked_attribute MonitorEnter | MonitorExit expr -> trans_monitor_enter_exit context expr pc loc BuiltinDecl.__delete_locked_attribute MonitorExit diff --git a/infer/src/java/jTransExn.ml b/infer/src/java/jTransExn.ml index 404f4186a..c759587f3 100644 --- a/infer/src/java/jTransExn.ml +++ b/infer/src/java/jTransExn.ml @@ -70,8 +70,7 @@ let translate_exceptions (context : JContext.t) exit_nodes get_body_nodes handle | Some exn_class_name -> let exn_type = match - JTransType.get_class_type context.program (JContext.get_tenv context) - exn_class_name + JTransType.get_class_type context.program (JContext.get_tenv context) exn_class_name with | {Typ.desc= Tptr (typ, _)} -> typ diff --git a/infer/src/java/jTransType.ml b/infer/src/java/jTransType.ml index 05e6865e4..9d5551370 100644 --- a/infer/src/java/jTransType.ml +++ b/infer/src/java/jTransType.ml @@ -271,9 +271,7 @@ let add_model_fields program classpath_fields cn = try match JBasics.ClassMap.find cn (JClasspath.get_models program) with | Javalib.JClass _ as jclass -> - Javalib.cf_fold - (collect_models_class_fields classpath_field_map cn) - jclass classpath_fields + Javalib.cf_fold (collect_models_class_fields classpath_field_map cn) jclass classpath_fields | _ -> classpath_fields with Caml.Not_found -> classpath_fields @@ -349,9 +347,7 @@ and get_class_struct_typ = Tenv.mk_struct tenv name | Some node -> let create_super_list interface_names = - List.iter - ~f:(fun cn -> ignore (get_class_struct_typ program tenv cn)) - interface_names ; + List.iter ~f:(fun cn -> ignore (get_class_struct_typ program tenv cn)) interface_names ; List.map ~f:typename_of_classname interface_names in let supers, fields, statics, annots = diff --git a/infer/src/labs/00_dummy_checker/ResourceLeaks.ml b/infer/src/labs/00_dummy_checker/ResourceLeaks.ml index 754586622..07eb60e05 100644 --- a/infer/src/labs/00_dummy_checker/ResourceLeaks.ml +++ b/infer/src/labs/00_dummy_checker/ResourceLeaks.ml @@ -53,8 +53,8 @@ module TransferFunctions (CFG : ProcCfg.S) = struct (** Take an abstract state and instruction, produce a new abstract state *) - let exec_instr (astate : ResourceLeakDomain.t) {ProcData.pdesc= _; tenv= _} _ - (instr : HilInstr.t) = + let exec_instr (astate : ResourceLeakDomain.t) {ProcData.pdesc= _; tenv= _} _ (instr : HilInstr.t) + = match instr with | Call (_return_opt, Direct _callee_procname, _actuals, _, _loc) -> (* function call [return_opt] := invoke [callee_procname]([actuals]) *) @@ -75,9 +75,9 @@ module TransferFunctions (CFG : ProcCfg.S) = struct let pp_session_name _node fmt = F.pp_print_string fmt "resource leaks" end +module CFG = ProcCfg.Normal (** 5(a) Type of CFG to analyze--Exceptional to follow exceptional control-flow edges, Normal to ignore them *) -module CFG = ProcCfg.Normal (* Create an intraprocedural abstract interpreter from the transfer functions we defined *) module Analyzer = LowerHil.MakeAbstractInterpreter (TransferFunctions (CFG)) diff --git a/infer/src/labs/01_integer_domain/ResourceLeaks.ml b/infer/src/labs/01_integer_domain/ResourceLeaks.ml index 0b7d3c693..6225a0d71 100644 --- a/infer/src/labs/01_integer_domain/ResourceLeaks.ml +++ b/infer/src/labs/01_integer_domain/ResourceLeaks.ml @@ -77,9 +77,9 @@ module TransferFunctions (CFG : ProcCfg.S) = struct let pp_session_name _node fmt = F.pp_print_string fmt "resource leaks" end +module CFG = ProcCfg.Normal (** 5(a) Type of CFG to analyze--Exceptional to follow exceptional control-flow edges, Normal to ignore them *) -module CFG = ProcCfg.Normal (* Create an intraprocedural abstract interpreter from the transfer functions we defined *) module Analyzer = LowerHil.MakeAbstractInterpreter (TransferFunctions (CFG)) diff --git a/infer/src/labs/02_domain_join/ResourceLeaks.ml b/infer/src/labs/02_domain_join/ResourceLeaks.ml index 0b7d3c693..6225a0d71 100644 --- a/infer/src/labs/02_domain_join/ResourceLeaks.ml +++ b/infer/src/labs/02_domain_join/ResourceLeaks.ml @@ -77,9 +77,9 @@ module TransferFunctions (CFG : ProcCfg.S) = struct let pp_session_name _node fmt = F.pp_print_string fmt "resource leaks" end +module CFG = ProcCfg.Normal (** 5(a) Type of CFG to analyze--Exceptional to follow exceptional control-flow edges, Normal to ignore them *) -module CFG = ProcCfg.Normal (* Create an intraprocedural abstract interpreter from the transfer functions we defined *) module Analyzer = LowerHil.MakeAbstractInterpreter (TransferFunctions (CFG)) diff --git a/infer/src/labs/03_domain_top/ResourceLeaks.ml b/infer/src/labs/03_domain_top/ResourceLeaks.ml index 0b7d3c693..6225a0d71 100644 --- a/infer/src/labs/03_domain_top/ResourceLeaks.ml +++ b/infer/src/labs/03_domain_top/ResourceLeaks.ml @@ -77,9 +77,9 @@ module TransferFunctions (CFG : ProcCfg.S) = struct let pp_session_name _node fmt = F.pp_print_string fmt "resource leaks" end +module CFG = ProcCfg.Normal (** 5(a) Type of CFG to analyze--Exceptional to follow exceptional control-flow edges, Normal to ignore them *) -module CFG = ProcCfg.Normal (* Create an intraprocedural abstract interpreter from the transfer functions we defined *) module Analyzer = LowerHil.MakeAbstractInterpreter (TransferFunctions (CFG)) diff --git a/infer/src/labs/04_interprocedural/ResourceLeaks.ml b/infer/src/labs/04_interprocedural/ResourceLeaks.ml index 71a6e563f..8a0c2ccb1 100644 --- a/infer/src/labs/04_interprocedural/ResourceLeaks.ml +++ b/infer/src/labs/04_interprocedural/ResourceLeaks.ml @@ -91,9 +91,9 @@ module TransferFunctions (CFG : ProcCfg.S) = struct let pp_session_name _node fmt = F.pp_print_string fmt "resource leaks lab" end +module CFG = ProcCfg.Normal (** 5(a) Type of CFG to analyze--Exceptional to follow exceptional control-flow edges, Normal to ignore them *) -module CFG = ProcCfg.Normal (* Create an intraprocedural abstract interpreter from the transfer functions we defined *) module Analyzer = LowerHil.MakeAbstractInterpreter (TransferFunctions (CFG)) diff --git a/infer/src/labs/05_access_paths_interprocedural/ResourceLeakDomain.ml b/infer/src/labs/05_access_paths_interprocedural/ResourceLeakDomain.ml index f133d3cff..a2a6dd680 100644 --- a/infer/src/labs/05_access_paths_interprocedural/ResourceLeakDomain.ml +++ b/infer/src/labs/05_access_paths_interprocedural/ResourceLeakDomain.ml @@ -150,8 +150,7 @@ module Summary = struct | Formal i -> ( match List.nth actuals i with | Some (HilExp.AccessExpression actual_expr) -> - Some - (AccessPath.append (HilExp.AccessExpression.to_access_path actual_expr) accesses) + Some (AccessPath.append (HilExp.AccessExpression.to_access_path actual_expr) accesses) | _ -> None ) in diff --git a/infer/src/labs/05_access_paths_interprocedural/ResourceLeaks.ml b/infer/src/labs/05_access_paths_interprocedural/ResourceLeaks.ml index b9407f01a..f28d20a8e 100644 --- a/infer/src/labs/05_access_paths_interprocedural/ResourceLeaks.ml +++ b/infer/src/labs/05_access_paths_interprocedural/ResourceLeaks.ml @@ -98,9 +98,9 @@ module TransferFunctions (CFG : ProcCfg.S) = struct let pp_session_name _node fmt = F.pp_print_string fmt "resource leaks lab" end +module CFG = ProcCfg.Normal (** 5(a) Type of CFG to analyze--Exceptional to follow exceptional control-flow edges, Normal to ignore them *) -module CFG = ProcCfg.Normal (* Create an intraprocedural abstract interpreter from the transfer functions we defined *) module Analyzer = LowerHil.MakeAbstractInterpreter (TransferFunctions (CFG)) diff --git a/infer/src/labs/ResourceLeaks.ml b/infer/src/labs/ResourceLeaks.ml index 0e5ea7058..206cef2a6 100644 --- a/infer/src/labs/ResourceLeaks.ml +++ b/infer/src/labs/ResourceLeaks.ml @@ -75,9 +75,9 @@ module TransferFunctions (CFG : ProcCfg.S) = struct let pp_session_name _node fmt = F.pp_print_string fmt "resource leaks" end +module CFG = ProcCfg.Normal (** 5(a) Type of CFG to analyze--Exceptional to follow exceptional control-flow edges, Normal to ignore them *) -module CFG = ProcCfg.Normal (* Create an intraprocedural abstract interpreter from the transfer functions we defined *) module Analyzer = LowerHil.MakeAbstractInterpreter (TransferFunctions (CFG)) diff --git a/infer/src/nullsafe/AnnotatedSignature.ml b/infer/src/nullsafe/AnnotatedSignature.ml index 0889ac340..c634efdca 100644 --- a/infer/src/nullsafe/AnnotatedSignature.ml +++ b/infer/src/nullsafe/AnnotatedSignature.ml @@ -120,13 +120,13 @@ let param_has_annot predicate pvar ann_sig = let pp proc_name fmt annotated_signature = let pp_ia fmt ia = if ia <> [] then F.fprintf fmt "%a " Annot.Item.pp ia in let pp_annotated_param fmt {mangled; param_annotation_deprecated; param_annotated_type} = - F.fprintf fmt " %a%a %a" pp_ia param_annotation_deprecated AnnotatedType.pp - param_annotated_type Mangled.pp mangled + F.fprintf fmt " %a%a %a" pp_ia param_annotation_deprecated AnnotatedType.pp param_annotated_type + Mangled.pp mangled in let {ret_annotation_deprecated; ret_annotated_type} = annotated_signature.ret in let mode_as_string = if annotated_signature.is_strict_mode then "Strict" else "Def" in - F.fprintf fmt "[%s] %a%a %a (%a )" mode_as_string pp_ia ret_annotation_deprecated - AnnotatedType.pp ret_annotated_type + F.fprintf fmt "[%s] %a%a %a (%a )" mode_as_string pp_ia ret_annotation_deprecated AnnotatedType.pp + ret_annotated_type (Typ.Procname.pp_simplified_string ~withclass:false) proc_name (Pp.comma_seq pp_annotated_param) annotated_signature.params diff --git a/infer/src/nullsafe/AssignmentRule.ml b/infer/src/nullsafe/AssignmentRule.ml index 406efae6a..d043d2574 100644 --- a/infer/src/nullsafe/AssignmentRule.ml +++ b/infer/src/nullsafe/AssignmentRule.ml @@ -6,14 +6,11 @@ *) open! IStd -type violation = {is_strict_mode: bool; lhs: Nullability.t; rhs: Nullability.t} -[@@deriving compare] +type violation = {is_strict_mode: bool; lhs: Nullability.t; rhs: Nullability.t} [@@deriving compare] type assignment_type = | PassingParamToFunction of - { param_description: string - ; param_position: int - ; function_procname: Typ.Procname.t } + {param_description: string; param_position: int; function_procname: Typ.Procname.t} | AssigningToField of Typ.Fieldname.t | ReturningFromFunction of Typ.Procname.t [@@deriving compare] @@ -24,7 +21,7 @@ let is_whitelisted_assignment ~is_strict_mode ~lhs ~rhs = (* We allow DeclaredNonnull -> Nonnull conversion outside of strict mode for better adoption. Otherwise using strictified classes in non-strict context becomes a pain because of extra warnings. - *) + *) true | _ -> false diff --git a/infer/src/nullsafe/AssignmentRule.mli b/infer/src/nullsafe/AssignmentRule.mli index 9679ad635..ee2df89ff 100644 --- a/infer/src/nullsafe/AssignmentRule.mli +++ b/infer/src/nullsafe/AssignmentRule.mli @@ -18,9 +18,7 @@ val check : type assignment_type = | PassingParamToFunction of - { param_description: string - ; param_position: int - ; function_procname: Typ.Procname.t } + {param_description: string; param_position: int; function_procname: Typ.Procname.t} | AssigningToField of Typ.Fieldname.t | ReturningFromFunction of Typ.Procname.t [@@deriving compare] diff --git a/infer/src/nullsafe/InferredNullability.ml b/infer/src/nullsafe/InferredNullability.ml index fa79be027..f00fb27f2 100644 --- a/infer/src/nullsafe/InferredNullability.ml +++ b/infer/src/nullsafe/InferredNullability.ml @@ -41,7 +41,7 @@ let join t1 t2 = (* Origin complements nullability information. It is the best effort to explain how was the nullability inferred. If nullability is fully determined by one of the arguments, origin should be get from this argument. Otherwise we apply heuristics to choose origin either from t1 or t2. - *) + *) let joined_origin = match (is_equal_to_t1, is_equal_to_t2) with | true, false -> @@ -53,7 +53,7 @@ let join t1 t2 = | false, false | true, true -> (* Nullability is not fully determined by neither t1 nor t2 Let TypeOrigin logic to decide what to prefer in this case. - *) + *) TypeOrigin.join t1.origin t2.origin in {nullability= joined_nullability; origin= joined_origin} diff --git a/infer/src/nullsafe/InheritanceRule.ml b/infer/src/nullsafe/InheritanceRule.ml index 36cd43a52..7ad36f61e 100644 --- a/infer/src/nullsafe/InheritanceRule.ml +++ b/infer/src/nullsafe/InheritanceRule.ml @@ -68,6 +68,5 @@ let violation_description _ violation_type ~base_proc_name ~overridden_proc_name Format.asprintf "%s parameter %a of method %a is not %a but is declared %ain the parent class method %a." (translate_position param_position) - MF.pp_monospaced param_description MF.pp_monospaced overridden_method_descr - MF.pp_monospaced nullable_annotation MF.pp_monospaced nullable_annotation MF.pp_monospaced - base_method_descr + MF.pp_monospaced param_description MF.pp_monospaced overridden_method_descr MF.pp_monospaced + nullable_annotation MF.pp_monospaced nullable_annotation MF.pp_monospaced base_method_descr diff --git a/infer/src/nullsafe/Initializers.ml b/infer/src/nullsafe/Initializers.ml index f53be88cc..a7ae61f4e 100644 --- a/infer/src/nullsafe/Initializers.ml +++ b/infer/src/nullsafe/Initializers.ml @@ -47,7 +47,7 @@ let final_typestates initializers_current_class tenv typecheck_proc = List.iter ~f:do_proc initializers ; !res in (* Get the initializers recursively called by computing a fixpoint. - Start from the initializers of the current class and the current procedure. *) + Start from the initializers of the current class and the current procedure. *) let initializers_recursive : init list = let initializers_base_case = initializers_current_class in let res = ref [] in @@ -121,12 +121,12 @@ let final_initializer_typestates_lazy tenv curr_pname curr_pdesc get_procs_in_fi Annotations.ia_is_initializer ia in let initializers_current_class = - pname_and_pdescs_with tenv curr_pname get_procs_in_file (function - | pname, proc_attributes -> + pname_and_pdescs_with tenv curr_pname get_procs_in_file (function pname, proc_attributes -> is_initializer proc_attributes && equal_class_opt (get_class pname) (get_class curr_pname) ) in - final_typestates ((curr_pname, curr_pdesc) :: initializers_current_class) tenv typecheck_proc) + final_typestates ((curr_pname, curr_pdesc) :: initializers_current_class) tenv typecheck_proc + ) (** Typestates after all constructors. *) @@ -137,4 +137,4 @@ let final_constructor_typestates_lazy tenv curr_pname get_procs_in_file typechec Typ.Procname.is_constructor pname && equal_class_opt (get_class pname) (get_class curr_pname) ) in - final_typestates constructors_current_class tenv typecheck_proc) + final_typestates constructors_current_class tenv typecheck_proc ) diff --git a/infer/src/nullsafe/NullabilityCheck.ml b/infer/src/nullsafe/NullabilityCheck.ml index d1908bb8f..955b75a5a 100644 --- a/infer/src/nullsafe/NullabilityCheck.ml +++ b/infer/src/nullsafe/NullabilityCheck.ml @@ -124,8 +124,8 @@ module TransferFunctions (CFG : ProcCfg.S) = struct if is_direct_dereference then (* direct dereference without intermediate variable *) F.asprintf - "The return value of %s is annotated with %a and is dereferenced without being \ - checked for null at %a" + "The return value of %s is annotated with %a and is dereferenced without being checked \ + for null at %a" (MF.monospaced_to_string simplified_pname) MF.pp_monospaced annotation Location.pp loc else @@ -242,7 +242,7 @@ module TransferFunctions (CFG : ProcCfg.S) = struct (* the rhs has type int when assigning the lhs to null *) if HilExp.is_null_literal rhs then true (* the lhs and rhs have the same type in the case of pointer assignment - but the types are different when assigning the pointee *) + but the types are different when assigning the pointee *) else match (AccessPath.get_typ lhs tenv, HilExp.get_typ tenv rhs) with (* defensive assumption when the types are not known *) @@ -273,11 +273,7 @@ module TransferFunctions (CFG : ProcCfg.S) = struct when is_non_objc_instance_method callee_pname -> check_ap proc_data loc (HilExp.AccessExpression.to_access_path receiver) astate | Call - ( ((_, ret_typ) as ret_var) - , Direct callee_pname - , HilExp.AccessExpression receiver :: _ - , _ - , _ ) + (((_, ret_typ) as ret_var), Direct callee_pname, HilExp.AccessExpression receiver :: _, _, _) when Typ.is_pointer ret_typ && is_objc_instance_method callee_pname -> ( match longest_nullable_prefix (HilExp.AccessExpression.to_access_path receiver) astate with | None -> diff --git a/infer/src/nullsafe/NullabilitySuggest.ml b/infer/src/nullsafe/NullabilitySuggest.ml index c1e7a3a3d..00c492d2f 100644 --- a/infer/src/nullsafe/NullabilitySuggest.ml +++ b/infer/src/nullsafe/NullabilitySuggest.ml @@ -70,8 +70,8 @@ module TransferFunctions (CFG : ProcCfg.S) = struct match Domain.find ap astate with | UseDefChain.NullDefCompare _ -> (* Stop NullDefCompare from propagating here because we want to prevent - * the checker from suggesting @Nullable on y in the following case: - * if (x == null) ... else { y = x; } *) + * the checker from suggesting @Nullable on y in the following case: + * if (x == null) ... else { y = x; } *) None | _ -> Some (UseDefChain.DependsOn (loc, ap)) @@ -195,9 +195,9 @@ let checker {Callbacks.summary; exe_env} = to be reported (the one that is using the field), but the root cause (the field with the wrong annotation itself). NOTE: Ideally we'd like to support such filtering in the way that - is agnostic to particular checker, but it is not trivial to - do, so let's do it in ad hoc way. - *) + is agnostic to particular checker, but it is not trivial to + do, so let's do it in ad hoc way. + *) () | Some (field_name, _) when Typ.Fieldname.Java.is_captured_parameter field_name -> (* Skip reporting when field comes from generated code *) diff --git a/infer/src/nullsafe/OverAnnotatedRule.ml b/infer/src/nullsafe/OverAnnotatedRule.ml index 9ef7915da..4f8e1d36f 100644 --- a/infer/src/nullsafe/OverAnnotatedRule.ml +++ b/infer/src/nullsafe/OverAnnotatedRule.ml @@ -17,8 +17,8 @@ let check ~what ~by_rhs_upper_bound = E.g. we technically can suggest changing [DeclaredNonnull] to [Nonnull], but in practice that requires strictification the code, which is a separate effort. - *) - Nullability.equal what Nullable + *) + Nullability.equal what Nullable then Error {declared_nullability= what; can_be_narrowed_to= by_rhs_upper_bound} else Ok () diff --git a/infer/src/nullsafe/ThirdPartyAnnotationInfo.ml b/infer/src/nullsafe/ThirdPartyAnnotationInfo.ml index c20d13c62..dd7279d90 100644 --- a/infer/src/nullsafe/ThirdPartyAnnotationInfo.ml +++ b/infer/src/nullsafe/ThirdPartyAnnotationInfo.ml @@ -24,8 +24,7 @@ let pp_parsing_error fmt {line_number; unparsable_method; parsing_error} = The evaluator function [f] has access to element's index. *) let bind_list_with_index list ~f = - List.foldi list ~init:(Ok ()) ~f:(fun index acc elem -> - Result.bind acc ~f:(fun _ -> f index elem) ) + List.foldi list ~init:(Ok ()) ~f:(fun index acc elem -> Result.bind acc ~f:(fun _ -> f index elem)) let parse_line_and_add_to_storage storage line = diff --git a/infer/src/nullsafe/eradicate.ml b/infer/src/nullsafe/eradicate.ml index cca5d8d02..2ab12d9ab 100644 --- a/infer/src/nullsafe/eradicate.ml +++ b/infer/src/nullsafe/eradicate.ml @@ -160,7 +160,8 @@ module MkCallback (Extension : ExtensionT) : CallBackT = struct EradicateChecks.check_constructor_initialization tenv find_canonical_duplicate curr_pname curr_pdesc start_node ~typestates_for_curr_constructor_and_all_initializer_methods ~typestates_for_all_constructors_incl_current proc_loc ; - if Config.eradicate_verbose then L.result "Final Typestate@\n%a@." TypeState.pp typestate ) + if Config.eradicate_verbose then L.result "Final Typestate@\n%a@." TypeState.pp typestate + ) in match typestate_opt with None -> () | Some typestate -> do_typestate typestate in @@ -207,8 +208,8 @@ module MkCallback (Extension : ExtensionT) : CallBackT = struct let linereader = Printer.LineReader.create () in if Config.eradicate_verbose then L.result "%a@." (AnnotatedSignature.pp proc_name) annotated_signature ; - callback2 tenv curr_pname calls_this checks callback_args annotated_signature linereader - loc ) ; + callback2 tenv curr_pname calls_this checks callback_args annotated_signature linereader loc + ) ; summary end diff --git a/infer/src/nullsafe/eradicateChecks.ml b/infer/src/nullsafe/eradicateChecks.ml index c1c5438a9..672bb9035 100644 --- a/infer/src/nullsafe/eradicateChecks.ml +++ b/infer/src/nullsafe/eradicateChecks.ml @@ -26,8 +26,8 @@ let is_virtual = function false -let check_object_dereference ~is_strict_mode tenv find_canonical_duplicate curr_pname node - instr_ref object_exp dereference_type inferred_nullability loc = +let check_object_dereference ~is_strict_mode tenv find_canonical_duplicate curr_pname node instr_ref + object_exp dereference_type inferred_nullability loc = Result.iter_error (DereferenceRule.check ~is_strict_mode (InferredNullability.get_nullability inferred_nullability)) @@ -181,7 +181,7 @@ let is_declared_nonnull AnnotatedField.{annotated_type} = (* Is field declared as non-nullable (implicitly or explicitly)? *) let is_field_declared_as_nonnull annotated_field_opt = (* If the field is not present, we optimistically assume it is not nullable. - TODO(T54687014) investigate if this leads to unsoundness issues in practice + TODO(T54687014) investigate if this leads to unsoundness issues in practice *) Option.exists annotated_field_opt ~f:is_declared_nonnull @@ -210,8 +210,8 @@ let get_nullability_upper_bound_for_typestate proc_name field_name typestate = match range_for_field with | None -> (* There is no information about the field type in typestate (field was not assigned in all paths). - It gives the most generic upper bound. - *) + It gives the most generic upper bound. + *) Nullability.top (* We were able to lookup the field. Its nullability gives precise upper bound. *) | Some (_, inferred_nullability) -> @@ -305,9 +305,7 @@ let check_constructor_initialization tenv find_canonical_duplicate curr_construc AnnotatedNullability.get_nullability annotated_field.annotated_type.nullability in - let by_rhs_upper_bound = - field_nullability_upper_bound_over_all_typestates () - in + let by_rhs_upper_bound = field_nullability_upper_bound_over_all_typestates () in Result.iter_error (OverAnnotatedRule.check ~what ~by_rhs_upper_bound) ~f:(fun over_annotated_violation -> report_error tenv find_canonical_duplicate @@ -328,8 +326,7 @@ let check_return_not_nullable ~is_strict_mode tenv find_canonical_duplicate loc (* Returning from a function is essentially an assignment the actual return value to the formal `return` *) let lhs = AnnotatedNullability.get_nullability ret_signature.ret_annotated_type.nullability in let rhs = InferredNullability.get_nullability ret_inferred_nullability in - Result.iter_error (AssignmentRule.check ~is_strict_mode ~lhs ~rhs) - ~f:(fun assignment_violation -> + Result.iter_error (AssignmentRule.check ~is_strict_mode ~lhs ~rhs) ~f:(fun assignment_violation -> let rhs_origin_descr = InferredNullability.descr_origin ret_inferred_nullability in report_error tenv find_canonical_duplicate (TypeErr.Bad_assignment @@ -346,7 +343,7 @@ let check_return_overrannotated tenv find_canonical_duplicate loc curr_pname cur (* In our CFG implementation, there is only one place where we return from a function (all execution flow joins are already made), hence inferreed nullability of returns gives us correct upper bound. - *) + *) let by_rhs_upper_bound = InferredNullability.get_nullability ret_inferred_nullability in Result.iter_error (OverAnnotatedRule.check ~what ~by_rhs_upper_bound) ~f:(fun over_annotated_violation -> @@ -414,13 +411,13 @@ let is_third_party_without_model proc_name = | Typ.Procname.Java java_pname -> (* TODO: migrate to the new way of checking for third party: use signatures repository instead of looking it up in config params. - *) + *) Typ.Procname.Java.is_external java_pname | _ -> false (* TODO: propagate the knowledge if it is a third-party or not in the annotated signature instead - of calculating it every time from scratch. - *) + of calculating it every time from scratch. + *) in is_third_party && (not (Models.is_modelled_for_nullability_as_internal proc_name)) @@ -452,7 +449,7 @@ let check_call_parameters ~is_strict_mode tenv find_canonical_duplicate curr_pde in if PatternMatch.type_is_class formal.param_annotated_type.typ then (* Passing a param to a function is essentially an assignment the actual param value - to the formal param *) + to the formal param *) let lhs = AnnotatedNullability.get_nullability formal.param_annotated_type.nullability in let rhs = InferredNullability.get_nullability nullability_actual in Result.iter_error (AssignmentRule.check ~is_strict_mode ~lhs ~rhs) ~f:report @@ -462,7 +459,7 @@ let check_call_parameters ~is_strict_mode tenv find_canonical_duplicate curr_pde Historically this is because there was no actionable way to change third party annotations. Now that we have such a support, this behavior might be reconsidered, provided our tooling and error reporting is friendly enough to be smoothly used by developers. - *) + *) let should_ignore_parameters_check = (* TODO(T52947663) model params in third-party non modelled method as a dedicated nullability type, so this logic can be moved to [AssignmentRule.check] *) @@ -528,7 +525,7 @@ let check_inheritance_rule_for_params find_canonical_duplicate tenv loc ~base_pr (AnnotatedNullability.get_nullability annotated_nullability_overridden) ) | Unequal_lengths -> (* Skip checking. - TODO (T5280249): investigate why argument lists can be of different length. *) + TODO (T5280249): investigate why argument lists can be of different length. *) () diff --git a/infer/src/nullsafe/modelTables.ml b/infer/src/nullsafe/modelTables.ml index 37c3ab2e8..bfabdf067 100644 --- a/infer/src/nullsafe/modelTables.ml +++ b/infer/src/nullsafe/modelTables.ml @@ -103,9 +103,7 @@ let check_not_null_parameter_list, check_not_null_list = ; ( 1 , (o, [x]) , "com.google.common.base.Preconditions.checkNotNull(java.lang.Object):java.lang.Object" ) - ; ( 1 - , (o, [x]) - , "com.google.common.base.Verify.verifyNotNull(java.lang.Object):java.lang.Object" ) + ; (1, (o, [x]), "com.google.common.base.Verify.verifyNotNull(java.lang.Object):java.lang.Object") ; ( 1 , (o, [x; n; n]) , "com.google.common.base.Verify.verifyNotNull(java.lang.Object,java.lang.String,java.lang.Object[]):java.lang.Object" @@ -150,8 +148,7 @@ let check_state_list = , "com.facebook.infer.annotation.Assertions.assertCondition(boolean,java.lang.String):void" ) ; ((o, [n]), "com.facebook.infer.annotation.Assertions.assumeCondition(boolean):void") ; ( (o, [n; o]) - , "com.facebook.infer.annotation.Assertions.assumeCondition(boolean,java.lang.String):void" ) - ] + , "com.facebook.infer.annotation.Assertions.assumeCondition(boolean,java.lang.String):void" ) ] let check_argument_list = @@ -379,9 +376,7 @@ let annotated_list_nullability = ; ( (n, [o]) , "javax.lang.model.element.Element.getAnnotation(java.lang.Class):java.lang.annotation.Annotation" ) - ; ( ng - , "javax.lang.model.element.Element.getEnclosingElement():javax.lang.model.element.Element" - ) + ; (ng, "javax.lang.model.element.Element.getEnclosingElement():javax.lang.model.element.Element") ; ( ng , "javax.lang.model.element.ExecutableElement.getDefaultValue():javax.lang.model.element.AnnotationValue" ) diff --git a/infer/src/nullsafe/models.ml b/infer/src/nullsafe/models.ml index 0f2e382a8..bdc10d17a 100644 --- a/infer/src/nullsafe/models.ml +++ b/infer/src/nullsafe/models.ml @@ -98,7 +98,7 @@ let get_modelled_annotated_signature tenv proc_attributes = (** Return true when the procedure has been modelled for nullability. *) let is_modelled_for_nullability_as_internal proc_name = (* TODO: get rid of this function, and propagate this information in get_modelled_annotated_signature instead - to avoid double calculation and make the code more clear. + to avoid double calculation and make the code more clear. *) let proc_id = Typ.Procname.to_unique_id proc_name in try diff --git a/infer/src/nullsafe/typeCheck.ml b/infer/src/nullsafe/typeCheck.ml index 2d4c76990..b0b7783cb 100644 --- a/infer/src/nullsafe/typeCheck.ml +++ b/infer/src/nullsafe/typeCheck.ml @@ -101,8 +101,7 @@ end (* ComplexExpressions *) -type check_return_type = - Typ.Procname.t -> Procdesc.t -> Typ.t -> Typ.t option -> Location.t -> unit +type check_return_type = Typ.Procname.t -> Procdesc.t -> Typ.t -> Typ.t option -> Location.t -> unit type find_canonical_duplicate = Procdesc.Node.t -> Procdesc.Node.t @@ -270,8 +269,8 @@ let convert_complex_exp_to_pvar tenv idenv curr_pname in match frontend_variable_assignment with | Some (call_node, id) -> - handle_function_call tenv curr_pname typestate exp default ~is_assignment ~call_node - ~node id + handle_function_call tenv curr_pname typestate exp default ~is_assignment ~call_node ~node + id | _ -> default ) | Exp.Lvar _ -> @@ -413,8 +412,8 @@ let pvar_apply instr_ref idenv tenv curr_pname curr_annotated_signature loc hand (* typecheck_expr with fewer parameters, using a common template for typestate range *) -let typecheck_expr_simple ~is_strict_mode find_canonical_duplicate curr_pdesc calls_this checks - tenv node instr_ref typestate1 exp1 typ1 origin1 loc1 = +let typecheck_expr_simple ~is_strict_mode find_canonical_duplicate curr_pdesc calls_this checks tenv + node instr_ref typestate1 exp1 typ1 origin1 loc1 = typecheck_expr ~is_strict_mode find_canonical_duplicate calls_this checks tenv node instr_ref curr_pdesc typestate1 exp1 (typ1, InferredNullability.create_nonnull origin1) @@ -431,8 +430,8 @@ let typecheck_expr_for_errors ~is_strict_mode find_canonical_duplicate curr_pdes (* Handle Preconditions.checkNotNull. *) let do_preconditions_check_not_null instr_ref tenv find_canonical_duplicate node loc curr_pdesc - curr_pname curr_annotated_signature checks call_params idenv parameter_num ~is_vararg - typestate' = + curr_pname curr_annotated_signature checks call_params idenv parameter_num ~is_vararg typestate' + = (* clear the nullable flag of the first parameter of the procedure *) let clear_nullable_flag typestate'' pvar = (* remove the nullable flag for the given pvar *) @@ -511,8 +510,8 @@ let do_preconditions_check_state instr_ref idenv tenv curr_pname curr_annotated_ let set_flag expression = let cond_e = Idenv.expand_expr_temps idenv cond_node expression in match - convert_complex_exp_to_pvar tenv idenv curr_pname curr_annotated_signature - ~node:cond_node ~original_node:node ~is_assignment:false cond_e typestate' loc + convert_complex_exp_to_pvar tenv idenv curr_pname curr_annotated_signature ~node:cond_node + ~original_node:node ~is_assignment:false cond_e typestate' loc with | Exp.Lvar pvar', _ -> set_nonnull pvar' @@ -538,7 +537,7 @@ let do_preconditions_check_state instr_ref idenv tenv curr_pname curr_annotated_ let branch = false in match Errdesc.find_boolean_assignment curr_node pvar branch with (* In foo(cond1 && cond2), the node that sets the result to false - has all the negated conditions as parents. *) + has all the negated conditions as parents. *) | Some boolean_assignment_node -> List.iter ~f:handle_negated_condition (Procdesc.Node.get_preds boolean_assignment_node) ; !res_typestate @@ -620,8 +619,7 @@ let rec normalize_cond_for_sil_prune_rec idenv ~node ~original_node cond = (node'', Exp.BinOp (bop, c1', c2')) | Exp.Var _ -> let c' = Idenv.expand_expr idenv cond in - if not (Exp.equal c' cond) then - normalize_cond_for_sil_prune_rec idenv ~node ~original_node c' + if not (Exp.equal c' cond) then normalize_cond_for_sil_prune_rec idenv ~node ~original_node c' else (node, c') | Exp.Lvar pvar when Pvar.is_frontend_tmp pvar -> ( match handle_assignment_in_condition_for_sil_prune idenv original_node pvar with @@ -809,8 +807,7 @@ let rec check_condition_for_sil_prune tenv idenv calls_this find_canonical_dupli (* If the function has @PropagatesNullable params the nullability of result is determined by nullability of actual values of these params. *) -let clarify_ret_by_propagates_nullable ret (resolved_params : EradicateChecks.resolved_param list) - = +let clarify_ret_by_propagates_nullable ret (resolved_params : EradicateChecks.resolved_param list) = (* Nullability of actual values of params that are marked as propagating nullables *) let nullability_of_propagates_nullable_params = List.filter_map resolved_params @@ -822,8 +819,8 @@ let clarify_ret_by_propagates_nullable ret (resolved_params : EradicateChecks.re ret | head :: tail -> (* We got non-empty list of params that propagate null. - It means that nullability of the return value will be determined by actual (inferred) nullability of them. - Joining their nullability will give us the least upper bound of nullability of the result *) + It means that nullability of the return value will be determined by actual (inferred) nullability of them. + Joining their nullability will give us the least upper bound of nullability of the result *) let upper_bound_nullability = List.fold tail ~init:head ~f:(fun acc nullability -> InferredNullability.join acc nullability ) @@ -890,15 +887,15 @@ let calc_typestate_after_call find_canonical_duplicate calls_this checks tenv id in let resolved_params = List.mapi ~f:resolve_param sig_call_params in (* Clarify function call result nullability based on params annotated with @PropagatesNullable - and inferred nullability of those params *) + and inferred nullability of those params *) let ret_respecting_propagates_nullable = clarify_ret_by_propagates_nullable preliminary_resolved_ret resolved_params in let typestate_after_call = if not is_anonymous_inner_class_constructor then ( if cflags.CallFlags.cf_virtual && checks.eradicate then - EradicateChecks.check_call_receiver ~is_strict_mode tenv find_canonical_duplicate - curr_pdesc node typestate1 call_params callee_pname instr_ref loc + EradicateChecks.check_call_receiver ~is_strict_mode tenv find_canonical_duplicate curr_pdesc + node typestate1 call_params callee_pname instr_ref loc (typecheck_expr ~is_strict_mode find_canonical_duplicate calls_this checks) ; if checks.eradicate then EradicateChecks.check_call_parameters ~is_strict_mode tenv find_canonical_duplicate @@ -912,8 +909,8 @@ let calc_typestate_after_call find_canonical_duplicate calls_this checks tenv id | None when Typ.Procname.Java.is_vararg callee_pname_java -> let last_parameter = List.length call_params in do_preconditions_check_not_null instr_ref tenv find_canonical_duplicate node loc - curr_pdesc curr_pname curr_annotated_signature checks call_params idenv - last_parameter ~is_vararg:true typestate1 + curr_pdesc curr_pname curr_annotated_signature checks call_params idenv last_parameter + ~is_vararg:true typestate1 | None -> (* assume the first parameter is checked for null *) do_preconditions_check_not_null instr_ref tenv find_canonical_duplicate node loc @@ -972,9 +969,7 @@ let typecheck_sil_call_function find_canonical_duplicate checks tenv instr_ref t in List.fold_right ~f:handle_et etl ~init:([], typestate) in - let callee_annotated_signature = - Models.get_modelled_annotated_signature tenv callee_attributes - in + let callee_annotated_signature = Models.get_modelled_annotated_signature tenv callee_attributes in let signature_params = drop_unchecked_signature_params callee_attributes callee_annotated_signature in @@ -1022,8 +1017,8 @@ let typecheck_instr tenv calls_this checks (node : Procdesc.Node.t) idenv curr_p ~original_node:node ~is_assignment:false e typestate loc in TypeState.add_id id - (typecheck_expr_simple ~is_strict_mode find_canonical_duplicate curr_pdesc calls_this - checks tenv node instr_ref typestate' e' typ TypeOrigin.Undef loc) + (typecheck_expr_simple ~is_strict_mode find_canonical_duplicate curr_pdesc calls_this checks + tenv node instr_ref typestate' e' typ TypeOrigin.Undef loc) typestate' | Sil.Store {e1= Exp.Lvar pvar; e2= Exp.Exn _} when is_return pvar -> (* skip assignment to return variable where it is an artifact of a throw instruction *) @@ -1061,8 +1056,7 @@ let typecheck_instr tenv calls_this checks (node : Procdesc.Node.t) idenv curr_p check_field_assign () ; typestate2 (* Java `new` operators *) | Sil.Call ((id, _), Exp.Const (Const.Cfun pn), [(_, typ)], _, _) - when Typ.Procname.equal pn BuiltinDecl.__new || Typ.Procname.equal pn BuiltinDecl.__new_array - -> + when Typ.Procname.equal pn BuiltinDecl.__new || Typ.Procname.equal pn BuiltinDecl.__new_array -> (* new never returns null *) TypeState.add_id id (typ, InferredNullability.create_nonnull TypeOrigin.New) typestate (* Type cast *) @@ -1076,8 +1070,8 @@ let typecheck_instr tenv calls_this checks (node : Procdesc.Node.t) idenv curr_p in (* cast copies the type of the first argument *) TypeState.add_id id - (typecheck_expr_simple ~is_strict_mode find_canonical_duplicate curr_pdesc calls_this - checks tenv node instr_ref typestate' e' typ TypeOrigin.ONone loc) + (typecheck_expr_simple ~is_strict_mode find_canonical_duplicate curr_pdesc calls_this checks + tenv node instr_ref typestate' e' typ TypeOrigin.ONone loc) typestate' (* myarray.length *) | Sil.Call ((id, _), Exp.Const (Const.Cfun pn), [(array_exp, t)], loc, _) @@ -1112,7 +1106,7 @@ let typecheck_instr tenv calls_this checks (node : Procdesc.Node.t) idenv curr_p | Sil.Call _ -> (* This is something weird, we don't normally expect this type of instruction This may be an unsoundness issue. - TODO(T54687014) investigate if this happens in production and add assertion, if not, and handle if gracefully, if yes. + TODO(T54687014) investigate if this happens in production and add assertion, if not, and handle if gracefully, if yes. *) typestate | Sil.Prune (cond, loc, true_branch, _) -> @@ -1147,8 +1141,7 @@ let typecheck_node tenv calls_this checks idenv curr_pname curr_pdesc find_canon if has_exceptions then typestates_exn := typestate :: !typestates_exn | Sil.Store {e1= Exp.Lvar pv} when Pvar.is_return pv - && Procdesc.Node.equal_nodekind (Procdesc.Node.get_kind node) Procdesc.Node.throw_kind - -> + && Procdesc.Node.equal_nodekind (Procdesc.Node.get_kind node) Procdesc.Node.throw_kind -> (* throw instruction *) typestates_exn := typestate :: !typestates_exn | _ -> diff --git a/infer/src/nullsafe/typeCheck.mli b/infer/src/nullsafe/typeCheck.mli index e1ea75534..48e701cf2 100644 --- a/infer/src/nullsafe/typeCheck.mli +++ b/infer/src/nullsafe/typeCheck.mli @@ -9,8 +9,7 @@ open! IStd (** Module type for the type checking functions. *) -type check_return_type = - Typ.Procname.t -> Procdesc.t -> Typ.t -> Typ.t option -> Location.t -> unit +type check_return_type = Typ.Procname.t -> Procdesc.t -> Typ.t -> Typ.t option -> Location.t -> unit type find_canonical_duplicate = Procdesc.Node.t -> Procdesc.Node.t diff --git a/infer/src/nullsafe/typeErr.ml b/infer/src/nullsafe/typeErr.ml index 57d9906f2..3fe6589f6 100644 --- a/infer/src/nullsafe/typeErr.ml +++ b/infer/src/nullsafe/typeErr.ml @@ -167,8 +167,7 @@ module Severity = struct match signature.params with | AnnotatedSignature.{mangled; param_annotated_type} :: _ when Mangled.is_this mangled -> (* TODO(T54088319) get rid of direct access to annotation *) - Option.bind ~f:get_severity - (PatternMatch.type_get_annotation tenv param_annotated_type.typ) + Option.bind ~f:get_severity (PatternMatch.type_get_annotation tenv param_annotated_type.typ) | _ -> None diff --git a/infer/src/pulse/Pulse.ml b/infer/src/pulse/Pulse.ml index b0fc0fcf6..b92821b70 100644 --- a/infer/src/pulse/Pulse.ml +++ b/infer/src/pulse/Pulse.ml @@ -170,16 +170,13 @@ module PulseTransferFunctions = struct [check_error summary result] | Prune (condition, loc, is_then_branch, if_kind) -> let post, cond_satisfiable = - PulseOperations.prune ~is_then_branch if_kind loc ~condition astate - |> check_error summary + PulseOperations.prune ~is_then_branch if_kind loc ~condition astate |> check_error summary in - if cond_satisfiable then - (* [condition] is true or unknown value: go into the branch *) + if cond_satisfiable then (* [condition] is true or unknown value: go into the branch *) [post] else (* [condition] is known to be unsatisfiable: prune path *) [] | Call (ret, call_exp, actuals, loc, call_flags) -> - dispatch_call tenv summary ret call_exp actuals loc call_flags astate - |> check_error summary + dispatch_call tenv summary ret call_exp actuals loc call_flags astate |> check_error summary | Metadata (ExitScope (vars, location)) -> [PulseOperations.remove_vars vars location astate] | Metadata (VariableLifetimeBegins (pvar, _, location)) -> diff --git a/infer/src/pulse/PulseAbductiveDomain.ml b/infer/src/pulse/PulseAbductiveDomain.ml index bd11de4e6..45defb40c 100644 --- a/infer/src/pulse/PulseAbductiveDomain.ml +++ b/infer/src/pulse/PulseAbductiveDomain.ml @@ -346,9 +346,7 @@ module PrePost = struct type cannot_apply_pre = | Aliasing of - { addr_caller: AbstractValue.t - ; addr_callee: AbstractValue.t - ; addr_callee': AbstractValue.t } + {addr_caller: AbstractValue.t; addr_callee: AbstractValue.t; addr_callee': AbstractValue.t} (** raised when the precondition and the current state disagree on the aliasing, i.e. some addresses [callee_addr] and [callee_addr'] that are distinct in the pre are aliased to a single address [caller_addr] in the caller's current state. Typically raised when @@ -391,9 +389,11 @@ module PrePost = struct let pp_call_state fmt {astate; subst; rev_subst; visited} = F.fprintf fmt - "@[{ astate=@[%a@];@, subst=@[%a@];@, rev_subst=@[%a@];@, \ - visited=@[%a@]@, }@]" - pp astate + "@[{ astate=@[%a@];@,\ + \ subst=@[%a@];@,\ + \ rev_subst=@[%a@];@,\ + \ visited=@[%a@]@,\ + \ }@]" pp astate (AddressMap.pp ~pp_value:(fun fmt (addr, _) -> AbstractValue.pp fmt addr)) subst (AddressMap.pp ~pp_value:AbstractValue.pp) @@ -534,8 +534,8 @@ module PrePost = struct (fun (addr_dest_pre, _) (addr_dest_post, _) -> (* NOTE: ignores traces - TODO: can the traces be leveraged here? maybe easy to detect writes by looking at - the post trace *) + TODO: can the traces be leveraged here? maybe easy to detect writes by looking at + the post trace *) AbstractValue.equal addr_dest_pre addr_dest_post ) edges_pre edges_post in @@ -549,7 +549,7 @@ module PrePost = struct call_state = (* For each [(formal, actual)] pair, resolve them to addresses in their respective states then call [materialize_pre_from] on them. Give up if calling the function introduces aliasing. - *) + *) match IList.fold2_result formals actuals ~init:call_state ~f:(fun call_state formal (actual, _) -> materialize_pre_from_actual callee_proc_name call_location @@ -617,7 +617,7 @@ module PrePost = struct BaseMemory.Edges.merge (fun _access old_opt pre_opt -> (* TODO: should apply [call_state.subst] to [_access]! Actually, should rewrite the - whole [cell_pre] beforehand so that [Edges.merge] makes sense. *) + whole [cell_pre] beforehand so that [Edges.merge] makes sense. *) if Option.is_some pre_opt then (* delete edge if some edge for the same access exists in the pre *) None @@ -717,9 +717,8 @@ module PrePost = struct record_post_cell callee_proc_name call_loc ~addr_callee ~cell_pre_opt ~addr_hist_caller ~cell_post call_state in - IContainer.fold_of_pervasives_map_fold ~fold:Memory.Edges.fold - ~init:call_state_after_post edges_post - ~f:(fun call_state (_access, (addr_callee_dest, _)) -> + IContainer.fold_of_pervasives_map_fold ~fold:Memory.Edges.fold ~init:call_state_after_post + edges_post ~f:(fun call_state (_access, (addr_callee_dest, _)) -> let call_state, addr_hist_curr_dest = call_state_subst_find_or_new call_state addr_callee_dest ~default_hist_caller:(snd addr_hist_caller) @@ -775,13 +774,13 @@ module PrePost = struct (call_state, Some return_caller_addr_hist) ) - let apply_post_for_parameters callee_proc_name call_location pre_post ~formals ~actuals - call_state = + let apply_post_for_parameters callee_proc_name call_location pre_post ~formals ~actuals call_state + = (* for each [(formal_i, actual_i)] pair, do [post_i = post union subst(graph reachable from formal_i in post)], deleting previous info when comparing pre and post shows a difference (TODO: record in the pre when a location is written to instead of just comparing values between pre and post since it's unreliable, eg replace value read in pre with same value in - post but nuke other fields in the meantime? is that possible?). *) + post but nuke other fields in the meantime? is that possible?). *) match List.fold2 formals actuals ~init:call_state ~f:(fun call_state formal (actual, _) -> record_post_for_actual callee_proc_name call_location pre_post ~formal ~actual call_state @@ -837,8 +836,7 @@ module PrePost = struct let apply_post callee_proc_name call_location pre_post ~formals ~actuals call_state = PerfEvent.(log (fun logger -> log_begin_event logger ~name:"pulse call post" ())) ; let r = - apply_post_for_parameters callee_proc_name call_location pre_post ~formals ~actuals - call_state + apply_post_for_parameters callee_proc_name call_location pre_post ~formals ~actuals call_state |> apply_post_for_globals callee_proc_name call_location pre_post |> record_post_for_return callee_proc_name call_location pre_post |> fun (call_state, return_caller) -> @@ -877,8 +875,8 @@ module PrePost = struct (* - read all the pre, assert validity of addresses and materializes *everything* (to throw stuff - in the *current* pre as appropriate so that callers of the current procedure will also know - about the deeper reads) + in the *current* pre as appropriate so that callers of the current procedure will also know + about the deeper reads) - for each actual, write the post for that actual @@ -889,7 +887,7 @@ module PrePost = struct - what if some preconditions raise lifetime issues but others don't? Have to be careful with the noise that this will introduce since we don't care about values. For instance, if the pre is for a path where [formal != 0] and we pass [0] then it will be an FP. Maybe the solution is - to bake in some value analysis. *) + to bake in some value analysis. *) let apply callee_proc_name call_location pre_post ~formals ~actuals astate = L.d_printfln "Applying pre/post for %a(%a):@\n%a" Typ.Procname.pp callee_proc_name (Pp.seq ~sep:"," Var.pp) formals pp pre_post ; diff --git a/infer/src/pulse/PulseArithmetic.ml b/infer/src/pulse/PulseArithmetic.ml index 590fe74f9..d143efd47 100644 --- a/infer/src/pulse/PulseArithmetic.ml +++ b/infer/src/pulse/PulseArithmetic.ml @@ -203,22 +203,22 @@ let rec abduce_eq (a1 : t) (a2 : t) = | Outside (l1, u1), Outside (l2, u2) -> (* ∃x. (xu1) ∧ (xu2) ∧ li<=ui*) (* all the possible cases: - x: --------[ ]--------- - y: -----[ ]-------- + x: --------[ ]--------- + y: -----[ ]-------- - x: ---[ ]------ - y: -----[ ]-------- + x: ---[ ]------ + y: -----[ ]-------- - x: ---[ ]---------- - y: -----[ ]-------- + x: ---[ ]---------- + y: -----[ ]-------- - x: ---------[ ]---- - y: -----[ ]-------- + x: ---------[ ]---- + y: -----[ ]-------- -> SAT, can tighten both to min(l1,l2)][max(u1,u2) - x: ---------------[ ]-- - y: -----[ ]-------- + x: ---------------[ ]-- + y: -----[ ]-------- or symmetrically x<->y => cannot express the 3 intervals that would be needed so return SAT (TODO: we might want to keep only one of these, which would be a kind of recency model of disequalities: remember the last known disequality) @@ -235,24 +235,24 @@ let rec abduce_eq (a1 : t) (a2 : t) = (* ∃x. l1≤x≤u1 ∧ (xu2) *) (* all the possible cases: - x: [-------] - y: --[ ]--- + x: [-------] + y: --[ ]--- case 1 above: SAT, cannot say more unless a1 is [-∞,+∞] (then we can abduce that a1 is the same as a2) - x: [--] - y: ------[ ]-- + x: [--] + y: ------[ ]-- case 2 above: UNSAT - x: [---] - y: ------[ ]-- + x: [---] + y: ------[ ]-- case 3 above: SAT: x = x\cap y for both - x: [----] - y: ------[ ]-- + x: [----] + y: ------[ ]-- case 4 above: SAT: x\cap y for both *) @@ -328,11 +328,11 @@ let abduce_le (a1 : t) (a2 : t) = (* two cases: 1. l1 (* similarly, two cases: 1. u1≥u2: can refine to x≤min(l1+1, u2) - x: -----[ ]--------------------- - y: ..-] + x: -----[ ]--------------------- + y: ..-] or y: ...-----] - 2. u1l2 *) @@ -385,8 +385,8 @@ let abduce_binop_constraints ~negated (bop : Binop.t) (a1 : t) (a2 : t) = let abduce_binop_is_true ~negated bop v1 v2 = - Logging.d_printfln "abduce_binop_is_true ~negated:%b %s (%a) (%a)" negated - (Binop.str Pp.text bop) (Pp.option pp) v1 (Pp.option pp) v2 ; + Logging.d_printfln "abduce_binop_is_true ~negated:%b %s (%a) (%a)" negated (Binop.str Pp.text bop) + (Pp.option pp) v1 (Pp.option pp) v2 ; match (v1, v2) with | None, None -> (* two existential variables: no way to express in the non-relational domain *) diff --git a/infer/src/pulse/PulseBaseDomain.ml b/infer/src/pulse/PulseBaseDomain.ml index 57dbfafaf..71fcee2b1 100644 --- a/infer/src/pulse/PulseBaseDomain.ml +++ b/infer/src/pulse/PulseBaseDomain.ml @@ -100,7 +100,7 @@ module GraphComparison = struct None | Some (edges, attrs) when Memory.Edges.is_empty edges && Attributes.is_empty attrs -> (* this can happen because of [register_address] or because we don't care to delete empty - edges when removing edges *) + edges when removing edges *) None | Some _ as some_cell -> some_cell @@ -146,8 +146,7 @@ module GraphComparison = struct match (stack_lhs, stack_rhs) with | [], [] -> IsomorphicUpTo mapping - | ( (var_lhs, (addr_lhs, _trace_lhs)) :: stack_lhs - , (var_rhs, (addr_rhs, _trace_rhs)) :: stack_rhs ) + | (var_lhs, (addr_lhs, _trace_lhs)) :: stack_lhs, (var_rhs, (addr_rhs, _trace_rhs)) :: stack_rhs when Var.equal var_lhs var_rhs -> ( match isograph_map_from_address ~lhs ~addr_lhs ~rhs ~addr_rhs mapping with | IsomorphicUpTo mapping -> @@ -182,7 +181,8 @@ module GraphVisit : sig var_filter:(Var.t -> bool) -> t -> init:'accum - -> f:( 'accum + -> f: + ( 'accum -> AbstractValue.t -> Var.t -> Memory.Access.t list diff --git a/infer/src/pulse/PulseDiagnostic.ml b/infer/src/pulse/PulseDiagnostic.ml index 940de1b85..724f827bc 100644 --- a/infer/src/pulse/PulseDiagnostic.ml +++ b/infer/src/pulse/PulseDiagnostic.ml @@ -14,9 +14,7 @@ module ValueHistory = PulseValueHistory type t = | AccessToInvalidAddress of - { invalidation: Invalidation.t - ; invalidation_trace: Trace.t - ; access_trace: Trace.t } + {invalidation: Invalidation.t; invalidation_trace: Trace.t; access_trace: Trace.t} | StackVariableAddressEscape of {variable: Var.t; history: ValueHistory.t; location: Location.t} let get_location = function @@ -58,8 +56,8 @@ let get_message = function | Immediate _ -> F.fprintf fmt "%a%a" Invalidation.describe invalidation pp_line line | ViaCall {f; _} -> - F.fprintf fmt "%a%a indirectly during the call to %a" Invalidation.describe - invalidation pp_line line CallEvent.describe f + F.fprintf fmt "%a%a indirectly during the call to %a" Invalidation.describe invalidation + pp_line line CallEvent.describe f in let invalidation_line = let {Location.line; _} = Trace.get_outer_location invalidation_trace in diff --git a/infer/src/pulse/PulseDiagnostic.mli b/infer/src/pulse/PulseDiagnostic.mli index fa69be4fe..3b94721d3 100644 --- a/infer/src/pulse/PulseDiagnostic.mli +++ b/infer/src/pulse/PulseDiagnostic.mli @@ -13,9 +13,7 @@ module ValueHistory = PulseValueHistory (** an error to report to the user *) type t = | AccessToInvalidAddress of - { invalidation: Invalidation.t - ; invalidation_trace: Trace.t - ; access_trace: Trace.t } + {invalidation: Invalidation.t; invalidation_trace: Trace.t; access_trace: Trace.t} | StackVariableAddressEscape of {variable: Var.t; history: ValueHistory.t; location: Location.t} val get_message : t -> string diff --git a/infer/src/pulse/PulseDomainInterface.ml b/infer/src/pulse/PulseDomainInterface.ml index faca03e80..63c89bced 100644 --- a/infer/src/pulse/PulseDomainInterface.ml +++ b/infer/src/pulse/PulseDomainInterface.ml @@ -6,14 +6,14 @@ *) open! IStd -(** if you do any mutations of the state in pulse you probably want this module *) module AbductiveDomain = PulseAbductiveDomain +(** if you do any mutations of the state in pulse you probably want this module *) module Stack = AbductiveDomain.Stack module Memory = AbductiveDomain.Memory -(** use only if you know what you are doing or you risk break bi-abduction *) module BaseDomain = PulseBaseDomain +(** use only if you know what you are doing or you risk break bi-abduction *) module BaseStack = PulseBaseStack module BaseMemory = PulseBaseMemory diff --git a/infer/src/pulse/PulseModels.ml b/infer/src/pulse/PulseModels.ml index 7a2cb9b03..4d2b91e20 100644 --- a/infer/src/pulse/PulseModels.ml +++ b/infer/src/pulse/PulseModels.ml @@ -54,8 +54,7 @@ module C = struct fun ~caller_summary:_ location ~ret:_ ~actuals astate -> match actuals with | [(deleted_access, _)] -> - PulseOperations.invalidate location Invalidation.CFree deleted_access astate - >>| List.return + PulseOperations.invalidate location Invalidation.CFree deleted_access astate >>| List.return | _ -> Ok [astate] end @@ -129,9 +128,7 @@ module StdFunction = struct let operator_call : model = fun ~caller_summary location ~ret ~actuals astate -> let havoc_ret (ret_id, _) astate = - let event = - ValueHistory.Call {f= Model "std::function::operator()"; location; in_call= []} - in + let event = ValueHistory.Call {f= Model "std::function::operator()"; location; in_call= []} in [PulseOperations.havoc_id ret_id [event] astate] in match actuals with diff --git a/infer/src/pulse/PulseOperations.ml b/infer/src/pulse/PulseOperations.ml index f2c9da9ef..dd46437fa 100644 --- a/infer/src/pulse/PulseOperations.ml +++ b/infer/src/pulse/PulseOperations.ml @@ -36,8 +36,7 @@ module Closures = struct let is_captured_fake_access (access : _ HilExp.Access.t) = match access with | FieldAccess fieldname - when String.is_prefix ~prefix:fake_capture_field_prefix (Typ.Fieldname.to_string fieldname) - -> + when String.is_prefix ~prefix:fake_capture_field_prefix (Typ.Fieldname.to_string fieldname) -> true | _ -> false diff --git a/infer/src/pulse/PulseTrace.ml b/infer/src/pulse/PulseTrace.ml index d82af5f3c..51d963e4d 100644 --- a/infer/src/pulse/PulseTrace.ml +++ b/infer/src/pulse/PulseTrace.ml @@ -33,8 +33,7 @@ let rec pp ~pp_immediate fmt trace = | Immediate {location= _; history} -> F.fprintf fmt "%a::%t" ValueHistory.pp history pp_immediate | ViaCall {f; location= _; history; in_call} -> - F.fprintf fmt "%a::%a[%a]" ValueHistory.pp history CallEvent.pp f (pp ~pp_immediate) - in_call + F.fprintf fmt "%a::%a[%a]" ValueHistory.pp history CallEvent.pp f (pp ~pp_immediate) in_call let add_event event = function diff --git a/infer/src/quandary/ClangTaintAnalysis.ml b/infer/src/quandary/ClangTaintAnalysis.ml index 0818fe43f..f1961861c 100644 --- a/infer/src/quandary/ClangTaintAnalysis.ml +++ b/infer/src/quandary/ClangTaintAnalysis.ml @@ -48,7 +48,7 @@ include TaintAnalysis.Make (struct [TaintSpec.Propagate_to_receiver] in (* if we have a specific model for a procedure, use that. otherwise, use the generic - heuristics for dealing with unknown code *) + heuristics for dealing with unknown code *) match Typ.Procname.get_method pname with | "operator+=" | "operator-=" @@ -73,17 +73,17 @@ include TaintAnalysis.Make (struct (* treat folly functions as unknown library code. we often specify folly functions as sinks, - and we don't want to double-report if these functions eventually call other sinks (e.g., - when folly::Subprocess calls exec), in addition some folly functions are heavily optimized in - a way that obscures what they're actually doing (e.g., they use assembly code). it's better - to write models for these functions or treat them as unknown *) + and we don't want to double-report if these functions eventually call other sinks (e.g., + when folly::Subprocess calls exec), in addition some folly functions are heavily optimized in + a way that obscures what they're actually doing (e.g., they use assembly code). it's better + to write models for these functions or treat them as unknown *) let models_matcher = QualifiedCppName.Match.of_fuzzy_qual_names ["folly"] let get_model pname ret_typ actuals tenv summary = (* hack for default C++ constructors, which get translated as an empty body (and will thus - have an empty summary). We don't want that because we want to be able to propagate taint - from comstructor parameters to the constructed object. so we treat the empty constructor - as a skip function instead *) + have an empty summary). We don't want that because we want to be able to propagate taint + from comstructor parameters to the constructed object. so we treat the empty constructor + as a skip function instead *) let is_default_constructor pname = Typ.Procname.is_c_method pname && Typ.Procname.is_constructor pname && AccessTree.BaseMap.is_empty summary diff --git a/infer/src/quandary/ClangTrace.ml b/infer/src/quandary/ClangTrace.ml index 99c4c0ce4..02603726a 100644 --- a/infer/src/quandary/ClangTrace.ml +++ b/infer/src/quandary/ClangTrace.ml @@ -13,9 +13,9 @@ let parse_clang_procedure procedure kinds index = try Some (QualifiedCppName.Match.of_fuzzy_qual_names [procedure], kinds, index) with QualifiedCppName.ParseError _ -> (* Java and Clang sources/sinks live in the same inferconfig entry. If we try to parse a Java - procedure that happens to be an invalid Clang qualified name (e.g., MyClass.), - parsing will crash. In the future, we can avoid this by requiring JSON source/sink - specifications to indicate the language *) + procedure that happens to be an invalid Clang qualified name (e.g., MyClass.), + parsing will crash. In the future, we can avoid this by requiring JSON source/sink + specifications to indicate the language *) None @@ -480,8 +480,8 @@ include Trace.Make (struct Option.some_if (is_injection_possible ~typ Sanitizer.EscapeURL sanitizers) IssueType.untrusted_url_risk - | ( (CommandLineFlag (_, typ) | Endpoint (_, typ) | UserControlledEndpoint (_, typ)) - , SQLInjection ) -> + | (CommandLineFlag (_, typ) | Endpoint (_, typ) | UserControlledEndpoint (_, typ)), SQLInjection + -> if is_injection_possible ~typ Sanitizer.EscapeSQL sanitizers then (* SQL injection if the caller of the endpoint doesn't sanitize on its end *) Some IssueType.sql_injection_risk @@ -494,8 +494,7 @@ include Trace.Make (struct | (Endpoint _ | UserControlledEndpoint _), EnvironmentChange -> (* user-controlled environment mutation *) Some IssueType.untrusted_environment_change_risk - | (CommandLineFlag (_, typ) | Endpoint (_, typ) | UserControlledEndpoint (_, typ)), ShellExec - -> + | (CommandLineFlag (_, typ) | Endpoint (_, typ) | UserControlledEndpoint (_, typ)), ShellExec -> (* code injection if the caller of the endpoint doesn't sanitize on its end *) Option.some_if (is_injection_possible ~typ Sanitizer.EscapeShell sanitizers) diff --git a/infer/src/quandary/JavaTaintAnalysis.ml b/infer/src/quandary/JavaTaintAnalysis.ml index f005cdac4..dd83dd05f 100644 --- a/infer/src/quandary/JavaTaintAnalysis.ml +++ b/infer/src/quandary/JavaTaintAnalysis.ml @@ -49,7 +49,7 @@ include TaintAnalysis.Make (struct with | "android.content.Intent", ("putExtra" | "putExtras"), _ -> (* don't care about tainted extras. instead. we'll check that result of getExtra is - always used safely *) + always used safely *) [] | _ when Typ.Procname.is_constructor pname -> [TaintSpec.Propagate_to_receiver] @@ -63,8 +63,8 @@ include TaintAnalysis.Make (struct when (not is_static) && types_match (get_receiver_typ tenv receiver_exp) classname tenv -> (* if the receiver and return type are the same, propagate to both. we're - assuming the call is one of the common "builder-style" methods that both - updates and returns the receiver *) + assuming the call is one of the common "builder-style" methods that both + updates and returns the receiver *) [TaintSpec.Propagate_to_receiver; TaintSpec.Propagate_to_return] | _ -> (* receiver doesn't match return type; just propagate to the return type *) diff --git a/infer/src/quandary/JavaTrace.ml b/infer/src/quandary/JavaTrace.ml index f5dfd2fd7..7f1642e42 100644 --- a/infer/src/quandary/JavaTrace.ml +++ b/infer/src/quandary/JavaTrace.ml @@ -96,8 +96,8 @@ module SourceKind = struct Some [(Intent, return); (intent_for_insecure_intent_handling ~caller_pname, return)] | "android.support.v4.app.FragmentActivity", "getIntent" -> Some [(intent_for_insecure_intent_handling ~caller_pname, return)] - | "android.content.Intent", "" - when actual_has_type 2 "android.net.Uri" actuals tenv -> + | "android.content.Intent", "" when actual_has_type 2 "android.net.Uri" actuals tenv + -> (* taint the [this] parameter passed to the constructor *) Some [(IntentFromURI, Some 0)] | ( "android.content.Intent" @@ -179,9 +179,7 @@ module SourceKind = struct let taint_all_but_this ~make_source = List.map ~f:(fun (name, typ) -> - let taint = - if Mangled.is_this name then None else Some (make_source name typ.Typ.desc) - in + let taint = if Mangled.is_this name then None else Some (make_source name typ.Typ.desc) in (name, typ, taint) ) (Procdesc.get_formals pdesc) in @@ -604,8 +602,8 @@ include Trace.Make (struct -> (* untrusted data flows into JS *) Some IssueType.javascript_injection - | ( (Endpoint _ | Intent | IntentFromURI | UserControlledString | UserControlledURI) - , SQLInjection ) -> + | (Endpoint _ | Intent | IntentFromURI | UserControlledString | UserControlledURI), SQLInjection + -> (* untrusted and unescaped data flows to SQL *) Some IssueType.sql_injection_risk | ( (Endpoint _ | Intent | IntentFromURI | UserControlledString | UserControlledURI) diff --git a/infer/src/quandary/TaintAnalysis.ml b/infer/src/quandary/TaintAnalysis.ml index a47366e45..95ffdb73e 100644 --- a/infer/src/quandary/TaintAnalysis.ml +++ b/infer/src/quandary/TaintAnalysis.ml @@ -121,8 +121,7 @@ module Make (TaintSpecification : TaintSpec.S) = struct (** log any new reportable source-sink flows in [trace] *) - let report_trace ?(sink_indexes = IntSet.empty) trace cur_site (proc_data : extras ProcData.t) - = + let report_trace ?(sink_indexes = IntSet.empty) trace cur_site (proc_data : extras ProcData.t) = let get_summary pname = if Typ.Procname.equal pname (Summary.get_proc_name proc_data.summary) then (* read_summary will trigger ondemand analysis of the current proc. we don't want that. *) @@ -217,8 +216,8 @@ module Make (TaintSpecification : TaintSpec.S) = struct match List.find ~f:(fun sink -> - [%compare.equal: Sink.Kind.t] kind (Sink.kind sink) - && not (is_recursive sink) ) + [%compare.equal: Sink.Kind.t] kind (Sink.kind sink) && not (is_recursive sink) + ) (Sinks.elements (sinks trace)) with | Some matching_sink -> @@ -331,8 +330,7 @@ module Make (TaintSpecification : TaintSpec.S) = struct (TraceDomain.Sources.Footprint.is_bottom (TraceDomain.sources actual_trace').footprint) -> let actual_ap = - AccessPath.Abs.Abstracted - (HilExp.AccessExpression.to_access_path actual_ae_raw) + AccessPath.Abs.Abstracted (HilExp.AccessExpression.to_access_path actual_ae_raw) in TaintDomain.add_trace actual_ap actual_trace' access_tree_acc | _ -> @@ -361,9 +359,7 @@ module Make (TaintSpecification : TaintSpec.S) = struct None in let project ~formal_ap ~actual_ap = - let projected_ap = - AccessPath.append actual_ap (snd (AccessPath.Abs.extract formal_ap)) - in + let projected_ap = AccessPath.append actual_ap (snd (AccessPath.Abs.extract formal_ap)) in if AccessPath.Abs.is_exact formal_ap then AccessPath.Abs.Exact projected_ap else AccessPath.Abs.Abstracted projected_ap in @@ -437,8 +433,8 @@ module Make (TaintSpecification : TaintSpec.S) = struct (* not all sinks are function calls; we might want to treat an array or field access as a - sink too. do this by pretending an access is a call to a dummy function and using the - existing machinery for adding function call sinks *) + sink too. do this by pretending an access is a call to a dummy function and using the + existing machinery for adding function call sinks *) let add_sinks_for_access_path (proc_data : extras ProcData.t) access_expr loc astate = let rec add_sinks_for_access astate_acc = function | HilExp.AccessExpression.Base _ -> @@ -483,8 +479,7 @@ module Make (TaintSpecification : TaintSpec.S) = struct AccessPath.Abs.Exact (HilExp.AccessExpression.to_access_path access_expr) in let trace, subtree = - Option.value ~default:TaintDomain.empty_node - (TaintDomain.get_node access_path astate) + Option.value ~default:TaintDomain.empty_node (TaintDomain.get_node access_path astate) in TaintDomain.add_node access_path (TraceDomain.add_source source trace, subtree) astate ) @@ -595,8 +590,8 @@ module Make (TaintSpecification : TaintSpec.S) = struct | [AccessExpression lhs_access_expr; rhs_exp; HilExp.AccessExpression access_expr] -> ( let dummy_ret_access_expr = access_expr in match dummy_ret_access_expr with - | HilExp.AccessExpression.Base (Var.ProgramVar pvar, _) - when Pvar.is_frontend_tmp pvar -> + | HilExp.AccessExpression.Base (Var.ProgramVar pvar, _) when Pvar.is_frontend_tmp pvar + -> (* the frontend translates operator=(x, y) as operator=(x, y, dummy_ret) when operator= returns a value type *) exec_write proc_data lhs_access_expr rhs_exp access_tree @@ -618,8 +613,8 @@ module Make (TaintSpecification : TaintSpec.S) = struct match ret_ap with | _, {Typ.desc= Tvoid} when not (Typ.Procname.is_java callee_pname) -> ( (* the C++ frontend handles returns of non-pointers by adding a dummy - pass-by-reference variable as the last actual, then returning the value by - assigning to it. understand this pattern by pretending it's the return value *) + pass-by-reference variable as the last actual, then returning the value by + assigning to it. understand this pattern by pretending it's the return value *) match List.last actuals with | Some (HilExp.AccessExpression access_expr) -> ( match HilExp.AccessExpression.to_access_path access_expr with @@ -667,8 +662,8 @@ module Make (TaintSpecification : TaintSpec.S) = struct | Some model -> handle_model callee_pname astate_with_direct_sources model | None -> - apply_summary dummy_ret_opt actuals access_tree astate_with_direct_sources - proc_data call_site ) + apply_summary dummy_ret_opt actuals access_tree astate_with_direct_sources proc_data + call_site ) in let astate_with_sanitizer = match dummy_ret_opt with @@ -691,9 +686,9 @@ module Make (TaintSpecification : TaintSpec.S) = struct match instr with | Assign (Base (Var.ProgramVar pvar, _), HilExp.Exception _, _) when Pvar.is_return pvar -> (* the Java frontend translates `throw Exception` as `return Exception`, which is a bit - wonky. this translation causes problems for us in computing a summary when an - exception is "returned" from a void function. skip code like this for now, fix via - t14159157 later *) + wonky. this translation causes problems for us in computing a summary when an + exception is "returned" from a void function. skip code like this for now, fix via + t14159157 later *) astate | Assign (Base (Var.ProgramVar pvar, _), rhs_exp, _) when Pvar.is_return pvar && HilExp.is_null_literal rhs_exp diff --git a/infer/src/quandary/quandaryBO.ml b/infer/src/quandary/quandaryBO.ml index 8a100d958..8bf3ec45f 100644 --- a/infer/src/quandary/quandaryBO.ml +++ b/infer/src/quandary/quandaryBO.ml @@ -74,11 +74,10 @@ let update_issues all_issues = in let paired_issues = (* Can be computed more efficiently (in n*log(n)) by using a Map mapping - file name + line number to quandary_issues to match with inferbo_issues *) + file name + line number to quandary_issues to match with inferbo_issues *) List.concat_map quandary_issues ~f:(fun quandary_issue -> List.filter_map inferBO_issues ~f:(fun inferbo_issue -> - if matching_issues quandary_issue inferbo_issue then - Some (quandary_issue, inferbo_issue) + if matching_issues quandary_issue inferbo_issue then Some (quandary_issue, inferbo_issue) else None ) ) in let merge_issues (issue1, issue2) = diff --git a/infer/src/scripts/checkCopyright.ml b/infer/src/scripts/checkCopyright.ml index 57b8c275b..66c7e582e 100644 --- a/infer/src/scripts/checkCopyright.ml +++ b/infer/src/scripts/checkCopyright.ml @@ -274,8 +274,7 @@ let output_diff ~fname lines ?notice_range ?(monoidics = false) ?(ropas = false) for i = 0 to copy_lines_before do F.fprintf fmt "%s\n" lines.(i) done ; - if - starts_with_newline com_style && copy_lines_before > 0 && lines.(copy_lines_before - 1) <> "" + if starts_with_newline com_style && copy_lines_before > 0 && lines.(copy_lines_before - 1) <> "" then F.fprintf fmt "@\n" ; pp_copyright ~monoidics ~ropas com_style fmt ; for i = copy_lines_after to Array.length lines - 1 do diff --git a/infer/src/scuba/Scuba.ml b/infer/src/scuba/Scuba.ml index 9839b1128..56a17266e 100644 --- a/infer/src/scuba/Scuba.ml +++ b/infer/src/scuba/Scuba.ml @@ -20,7 +20,7 @@ type sample = let new_sample ~time = let time = match time with Some time -> time | None -> int_of_float (Unix.time ()) in { (* time is a single mandatory field in scuba. without it, - scuba disregards all samples *) + scuba disregards all samples *) int_section= SMap.singleton "time" time ; normal_section= SMap.empty } diff --git a/infer/src/test_determinator/testDeterminator.ml b/infer/src/test_determinator/testDeterminator.ml index 25aef038e..0252d57e4 100644 --- a/infer/src/test_determinator/testDeterminator.ml +++ b/infer/src/test_determinator/testDeterminator.ml @@ -59,7 +59,7 @@ end module DiffLines = struct (* This is a map - file name |--> {set of changed line } + file name |--> {set of changed line } *) (* Read the file containing info on changed lines and populate the map *) @@ -204,8 +204,8 @@ let java_test_to_run () = let remove_llvm_suffix_native_symbols native_symbols = let remove_llvm_suffix_native_symbol native_symbol = let remove_llvm_suffix name = - (* The first dot of .llvm.... is the first dot after the name, - because neither names nor mangled names can have dots. *) + (* The first dot of .llvm.... is the first dot after the name, + because neither names nor mangled names can have dots. *) match String.lsplit2 name ~on:'.' with | Some (name_no_suffix, _) -> name_no_suffix diff --git a/infer/src/topl/Topl.ml b/infer/src/topl/Topl.ml index 0ceb91979..8f89d9157 100644 --- a/infer/src/topl/Topl.ml +++ b/infer/src/topl/Topl.ml @@ -206,7 +206,7 @@ let is_inconsistent env query = let conjoin_props env post pre = (* PRE: p and q have no footprints: that would make no sense in pre/posts. *) (* TODO: Ideally, this should be boolean-conjunction. The function [Dom.prop_partial_meet] - comes close but fails in all practical cases. *) + comes close but fails in all practical cases. *) List.fold ~init:post ~f:(Prop.prop_atom_and env) (Prop.get_pure pre) diff --git a/infer/src/topl/ToplMonitor.ml b/infer/src/topl/ToplMonitor.ml index f74977066..8c7d70071 100644 --- a/infer/src/topl/ToplMonitor.ml +++ b/infer/src/topl/ToplMonitor.ml @@ -13,7 +13,7 @@ let sourcefile = let x = lazy (let pid = Pid.to_int (Unix.getpid ()) in - SourceFile.create (Printf.sprintf "SynthesizedToplProperty%d.java" pid)) + SourceFile.create (Printf.sprintf "SynthesizedToplProperty%d.java" pid) ) in fun () -> Lazy.force x @@ -139,7 +139,7 @@ let gen_if (cond : Exp.t) (true_branch : node_generator) (false_branch : node_ge false_branch create_node set_succs in (* NOTE: Symbolic execution works with non-pure prune expressions but it generates symbolic - states from which abstraction then removes too much information. *) + states from which abstraction then removes too much information. *) let cond, preamble = pure_exp cond in let prune_true = let node_type = Procdesc.Node.Prune_node (true, Sil.Ik_if, PruneNodeKind_MethodBody) in @@ -235,9 +235,7 @@ let generate_execute_state automaton proc_name = in let label = (ToplAutomaton.transition automaton t).label in let all_conjuncts = - let arg_conjunct i pattern = - conjunct (ToplUtils.static_var (ToplName.saved_arg i)) pattern - in + let arg_conjunct i pattern = conjunct (ToplUtils.static_var (ToplName.saved_arg i)) pattern in List.concat ( Option.value_map ~default:[] ~f:(fun x -> [x]) maybe :: [ToplUtils.static_var (ToplName.transition t)] @@ -314,8 +312,7 @@ let maybe_synthesize_it automaton proc_name = else if is_execute_state proc_name then Some (generate_execute_state automaton proc_name) else if is_maybe proc_name then Some (generate_maybe automaton proc_name) else - L.die InternalError - "TOPL instrumentation introduced a call to a method that is not generated" + L.die InternalError "TOPL instrumentation introduced a call to a method that is not generated" else None diff --git a/infer/src/unit/DifferentialFiltersTests.ml b/infer/src/unit/DifferentialFiltersTests.ml index 359232998..cc3723e58 100644 --- a/infer/src/unit/DifferentialFiltersTests.ml +++ b/infer/src/unit/DifferentialFiltersTests.ml @@ -227,6 +227,6 @@ let test_interesting_paths_filter = let tests = "differential_filters_suite" - >::: test_file_renamings_from_json @ test_file_renamings_find_previous - @ test_relative_complements @ test_interesting_paths_filter + >::: test_file_renamings_from_json @ test_file_renamings_find_previous @ test_relative_complements + @ test_interesting_paths_filter @ [test_skip_duplicated_types_on_filenames] diff --git a/infer/src/unit/DifferentialTestsUtils.ml b/infer/src/unit/DifferentialTestsUtils.ml index 8b090c0ad..a142923f7 100644 --- a/infer/src/unit/DifferentialTestsUtils.ml +++ b/infer/src/unit/DifferentialTestsUtils.ml @@ -7,12 +7,11 @@ open! IStd -let create_fake_jsonbug ?(bug_type = "bug_type") ?(qualifier = "qualifier") - ?(severity = "severity") ?(line = 1) ?(column = 1) ?(procedure = "procedure") - ?(procedure_start_line = 1) ?(file = "file/at/a/certain/path.java") ?(bug_trace = []) - ?(key = "File|method|TYPE") ?(node_key = Some "1234") ?(hash = "1") ?(dotty = None) - ?(infer_source_loc = None) ?(linters_def_file = Some "file/at/certain/path.al") ?doc_url () : - Jsonbug_t.jsonbug = +let create_fake_jsonbug ?(bug_type = "bug_type") ?(qualifier = "qualifier") ?(severity = "severity") + ?(line = 1) ?(column = 1) ?(procedure = "procedure") ?(procedure_start_line = 1) + ?(file = "file/at/a/certain/path.java") ?(bug_trace = []) ?(key = "File|method|TYPE") + ?(node_key = Some "1234") ?(hash = "1") ?(dotty = None) ?(infer_source_loc = None) + ?(linters_def_file = Some "file/at/certain/path.al") ?doc_url () : Jsonbug_t.jsonbug = { bug_type ; qualifier ; severity diff --git a/infer/src/unit/FileDiffTests.ml b/infer/src/unit/FileDiffTests.ml index 815c7e1a5..51378c599 100644 --- a/infer/src/unit/FileDiffTests.ml +++ b/infer/src/unit/FileDiffTests.ml @@ -19,9 +19,7 @@ let test_unixdiff_process_raw_directives_with_valid_input = in assert_equal ~cmp:(List.equal UnixDiffTest.equal) ~pp_diff expected found in - [ ( "test_unixdiff_process_raw_directives_1" - , "UOOU" - , UnixDiffTest.[Unchanged; Old; Old; Unchanged] ) + [ ("test_unixdiff_process_raw_directives_1", "UOOU", UnixDiffTest.[Unchanged; Old; Old; Unchanged]) ; ("test_unixdiff_process_raw_directives_2", "", []) ] |> List.map ~f:(fun (name, test_input, expected_output) -> name >:: create_test test_input expected_output ) @@ -80,12 +78,12 @@ let test_parse_directives_with_valid_input = in assert_equal ~cmp:(List.equal Int.equal) ~pp_diff expected found in - [ (* + [ (* === test1 === File1 and File2 are empty *) ("test_parse_directives_with_valid_input_1", [], []) - (* + (* === test2 === File1 File2 a x @@ -103,7 +101,7 @@ let test_parse_directives_with_valid_input = c Z *) ; ("test_parse_directives_with_valid_input_3", o 2 @ n 1 @ u 2 @ n 1, [1; 4]) - (* + (* === test4 === File1 File2 a w diff --git a/infer/src/unit/JavaProfilerSamplesTest.ml b/infer/src/unit/JavaProfilerSamplesTest.ml index 7d2c39afb..f671eaa84 100644 --- a/infer/src/unit/JavaProfilerSamplesTest.ml +++ b/infer/src/unit/JavaProfilerSamplesTest.ml @@ -166,8 +166,8 @@ let test_from_json_string_with_valid_input = let expected1 = [("label1", Typ.Procname.Set.of_list [])] in let input2 = Printf.sprintf - "[{\"foo\":{},\"test\": \"label1\",\"methods\": [{\"class\": \"ggg.hhh.Iii\", \"boo\": \ - \"\", \"method\": \"\", \"signature\": \"(Ljava/lang/String;[IJ)V\",\"wat\": \ + "[{\"foo\":{},\"test\": \"label1\",\"methods\": [{\"class\": \"ggg.hhh.Iii\", \"boo\": \"\", \ + \"method\": \"\", \"signature\": \"(Ljava/lang/String;[IJ)V\",\"wat\": \ \"\"},{\"class\": \"lll.mmm.Nnn\",\"boo\": \"\",\"method\": \"\",\"signature\": \ \"(Ljava/lang/String;[IJ)V\",\"wat\": \"\"}]},{\"boo\":\"aaa\",\"test\": \ \"label2\",\"methods\": [{\"class\": \"aaa.bbb.Ccc\",\"boo\": \"\",\"method\": \ diff --git a/infer/src/unit/TaintTests.ml b/infer/src/unit/TaintTests.ml index 41d44680e..dd65fe7da 100644 --- a/infer/src/unit/TaintTests.ml +++ b/infer/src/unit/TaintTests.ml @@ -77,8 +77,7 @@ let tests = in let pp_sinks fmt sinks = if MockTrace.Sinks.is_empty sinks then F.pp_print_char fmt '?' - else - MockTrace.Sinks.iter (fun sink -> pp_call_site fmt (MockTrace.Sink.call_site sink)) sinks + else MockTrace.Sinks.iter (fun sink -> pp_call_site fmt (MockTrace.Sink.call_site sink)) sinks in (* just print source -> sink, no line nums or passthroughs *) let pp_trace fmt trace = diff --git a/infer/src/unit/abstractInterpreterTests.ml b/infer/src/unit/abstractInterpreterTests.ml index adcb7cd1f..24132fa7b 100644 --- a/infer/src/unit/abstractInterpreterTests.ml +++ b/infer/src/unit/abstractInterpreterTests.ml @@ -88,8 +88,7 @@ let tests = ; If (unknown_exp, [], []) ; invariant "4" ] ) ; ("loop", [invariant "1"; While (unknown_exp, [invariant "T"]); invariant "T"]) - ; ( "if_in_loop" - , [While (unknown_exp, [If (unknown_exp, [], []); invariant "T"]); invariant "T"] ) + ; ("if_in_loop", [While (unknown_exp, [If (unknown_exp, [], []); invariant "T"]); invariant "T"]) ; ( "nested_loop_visit" , [ invariant "1" ; While (unknown_exp, [invariant "T"; While (unknown_exp, [invariant "T"]); invariant "T"]) diff --git a/infer/src/unit/accessPathTests.ml b/infer/src/unit/accessPathTests.ml index 96f379638..ba7e514fb 100644 --- a/infer/src/unit/accessPathTests.ml +++ b/infer/src/unit/accessPathTests.ml @@ -78,8 +78,8 @@ let tests = in let actual_ap = make_ap exp in let pp_diff fmt (actual_ap, expected_ap) = - F.fprintf fmt "Expected to make access path %a from expression %a, but got %a" - AccessPath.pp expected_ap Exp.pp exp AccessPath.pp actual_ap + F.fprintf fmt "Expected to make access path %a from expression %a, but got %a" AccessPath.pp + expected_ap Exp.pp exp AccessPath.pp actual_ap in assert_equal ~cmp:AccessPath.equal ~pp_diff actual_ap expected_ap in @@ -126,9 +126,7 @@ let tests = in let domain_test = let domain_test_ _ = - let pp_diff fmt (actual, expected) = - F.fprintf fmt "Expected %s but got %s" expected actual - in + let pp_diff fmt (actual, expected) = F.fprintf fmt "Expected %s but got %s" expected actual in let assert_eq input_aps expected = let input = F.asprintf "%a" AccessPathDomains.Set.pp input_aps in assert_equal ~cmp:String.equal ~pp_diff input expected @@ -149,8 +147,7 @@ let tests = assert_bool "mem_fuzzy_harder2" (AccessPathDomains.Set.mem_fuzzy x_abstract aps1) ; assert_bool "mem_fuzzy_negative" (not (AccessPathDomains.Set.mem_fuzzy y_exact aps1)) ; (* [mem_fuzzy] should behave the same as [mem] except in this case *) - assert_bool "mem_fuzzy_not_fully_contained" - (AccessPathDomains.Set.mem_fuzzy yF_abstract aps3) ; + assert_bool "mem_fuzzy_not_fully_contained" (AccessPathDomains.Set.mem_fuzzy yF_abstract aps3) ; assert_bool "<= on same is true" (AccessPathDomains.Set.leq ~lhs:aps1 ~rhs:aps1) ; assert_bool "aps1 <= aps2" (AccessPathDomains.Set.leq ~lhs:aps1 ~rhs:aps2) ; assert_bool "aps2 <= aps1" (AccessPathDomains.Set.leq ~lhs:aps2 ~rhs:aps1) ; diff --git a/infer/src/unit/addressTakenTests.ml b/infer/src/unit/addressTakenTests.ml index 0fe4c2d71..7a8e088c9 100644 --- a/infer/src/unit/addressTakenTests.ml +++ b/infer/src/unit/addressTakenTests.ml @@ -24,8 +24,7 @@ let tests = let test_list = [ ( "address_taken_set_instr" , [var_assign_addrof_var ~rhs_typ:int_ptr_typ "a" "b"; invariant "{ &b }"] ) - ; ( "address_not_taken_set_instr" - , [var_assign_addrof_var ~rhs_typ:int_typ "a" "b"; assert_empty] ) + ; ("address_not_taken_set_instr", [var_assign_addrof_var ~rhs_typ:int_typ "a" "b"; assert_empty]) ; ("address_not_taken_load_instr1", [id_assign_var ~rhs_typ:int_ptr_typ "a" "b"; assert_empty]) ; ("address_not_taken_load_instr2", [id_assign_var ~rhs_typ:int_typ "a" "b"; assert_empty]) ; ( "take_multiple_addresses" diff --git a/infer/src/unit/analyzerTester.ml b/infer/src/unit/analyzerTester.ml index 7e138d077..6d7d09953 100644 --- a/infer/src/unit/analyzerTester.ml +++ b/infer/src/unit/analyzerTester.ml @@ -297,7 +297,6 @@ module Make (T : TransferFunctions.SIL with type CFG.Node.t = Procdesc.Node.t) = List.concat_map ~f:(fun (name, test_program) -> List.map ai_list ~f:(fun (ai_name, create_test) -> - name ^ "_" ^ ai_name >:: create_test test_program extras ~initial pp_opt test_pname ) - ) + name ^ "_" ^ ai_name >:: create_test test_program extras ~initial pp_opt test_pname ) ) tests end diff --git a/infer/src/unit/procCfgTests.ml b/infer/src/unit/procCfgTests.ml index d134130cc..a033083b9 100644 --- a/infer/src/unit/procCfgTests.ml +++ b/infer/src/unit/procCfgTests.ml @@ -140,10 +140,7 @@ let tests = ; ("exn_succs_n2", ProcCfg.Exceptional.fold_exceptional_succs exceptional_proc_cfg, n2, [n3]) ; ("exn_succs_n3", ProcCfg.Exceptional.fold_exceptional_succs exceptional_proc_cfg, n3, [n4]) ; (* test exceptional pred links *) - ( "exn_preds_n3" - , ProcCfg.Exceptional.fold_exceptional_preds exceptional_proc_cfg - , n3 - , [n2; n1] ) + ("exn_preds_n3", ProcCfg.Exceptional.fold_exceptional_preds exceptional_proc_cfg, n3, [n2; n1]) ; (* succs should return both normal and exceptional successors *) ("exn_all_succs_n1", ProcCfg.Exceptional.fold_succs exceptional_proc_cfg, n1, [n3; n2]) ; (* but, should not return duplicates *) diff --git a/infer/src/unit/weakTopologicalOrderTests.ml b/infer/src/unit/weakTopologicalOrderTests.ml index 585ca9c4e..20f0fe769 100644 --- a/infer/src/unit/weakTopologicalOrderTests.ml +++ b/infer/src/unit/weakTopologicalOrderTests.ml @@ -18,9 +18,7 @@ let inputs = @ [ ( "bourdoncle_fig1" , [(1, [2]); (2, [3; 8]); (3, [4]); (4, [5; 7]); (5, [6]); (6, [5; 7]); (7, [3; 8])] , "1 2 (3 4 (5 6) 7) 8" ) - ; ( "bourdoncle_fig2left" - , [(1, [2; 4]); (2, [3]); (3, []); (4, [5; 3]); (5, [4])] - , "1 2 (4 5) 3" ) + ; ("bourdoncle_fig2left", [(1, [2; 4]); (2, [3]); (3, []); (4, [5; 3]); (5, [4])], "1 2 (4 5) 3") ; ("bourdoncle_fig2right", [(1, [2; 4]); (2, [3]); (3, [1]); (4, [3])], "(1 2 4 3)") ; ( "bourdoncle_fig5" , [ (1, [4; 2]) diff --git a/sledge/.ocamlformat b/sledge/.ocamlformat index 40b8a92ff..9d6fdf6d3 100644 --- a/sledge/.ocamlformat +++ b/sledge/.ocamlformat @@ -1,3 +1,4 @@ profile = compact -margin = 77 +break-before-in = fit-or-vertical +margin = 76 wrap-comments = true diff --git a/sledge/src/control.ml b/sledge/src/control.ml index e15941c63..5273fce5c 100644 --- a/sledge/src/control.ml +++ b/sledge/src/control.ml @@ -434,8 +434,8 @@ module Make (Dom : Domain_sig.Dom) = struct exec_skip_func stk state block areturn return | None -> exec_call opts stk state block {call with callee} - (Used_globals.by_function opts.globals callee.name.reg) - ) + (Used_globals.by_function opts.globals + callee.name.reg) ) |> Work.seq x ) ) | Return {exp} -> exec_return ~opts stk state block exp | Throw {exc} -> diff --git a/sledge/src/domain/itv.ml b/sledge/src/domain/itv.ml index 43e3a4da5..e1d68955c 100644 --- a/sledge/src/domain/itv.ml +++ b/sledge/src/domain/itv.ml @@ -32,8 +32,7 @@ let sexp_of_t (itv : t) = let sexps = Array.fold (bindings itv) ~init:[] ~f:(fun acc (v, {inf; sup}) -> Sexp.List - [ Sexp.Atom (Var.to_string v) - ; Sexp.Atom (Scalar.to_string inf) + [ Sexp.Atom (Var.to_string v); Sexp.Atom (Scalar.to_string inf) ; Sexp.Atom (Scalar.to_string sup) ] :: acc ) in diff --git a/sledge/src/domain/itv.mli b/sledge/src/domain/itv.mli index f9504d4c3..7f6309ae3 100644 --- a/sledge/src/domain/itv.mli +++ b/sledge/src/domain/itv.mli @@ -6,4 +6,5 @@ *) (** Interval abstract domain *) + include Domain_sig.Dom diff --git a/sledge/src/import/import.ml b/sledge/src/import/import.ml index b912ec52c..c7d240822 100644 --- a/sledge/src/import/import.ml +++ b/sledge/src/import/import.ml @@ -11,21 +11,22 @@ include ( Base : sig include - (module type of Base (* extended below, remove *) - with module Array := Base.Array - and module Invariant := Base.Invariant - and module List := Base.List - and module Map := Base.Map - and module Option := Base.Option - and module Result := Base.Result - and module Set := Base.Set - (* prematurely deprecated, remove and use Stdlib instead *) - and module Filename := Base.Filename - and module Format := Base.Format - and module Marshal := Base.Marshal - and module Scanf := Base.Scanf - and type ('ok, 'err) result := ('ok, 'err) Base.result) - [@warning "-3"] + (module type of Base + (* extended below, remove *) + with module Array := Base.Array + and module Invariant := Base.Invariant + and module List := Base.List + and module Map := Base.Map + and module Option := Base.Option + and module Result := Base.Result + and module Set := Base.Set + (* prematurely deprecated, remove and use Stdlib instead *) + and module Filename := Base.Filename + and module Format := Base.Format + and module Marshal := Base.Marshal + and module Scanf := Base.Scanf + and type ('ok, 'err) result := ('ok, 'err) Base.result + [@warning "-3"]) end ) (* undeprecate *) diff --git a/sledge/src/import/import.mli b/sledge/src/import/import.mli index 10ccb6072..a93c6ae91 100644 --- a/sledge/src/import/import.mli +++ b/sledge/src/import/import.mli @@ -11,21 +11,22 @@ include module type of ( Base : sig include - (module type of Base (* extended below, remove *) - with module Array := Base.Array - and module Invariant := Base.Invariant - and module List := Base.List - and module Map := Base.Map - and module Option := Base.Option - and module Result := Base.Result - and module Set := Base.Set - (* prematurely deprecated, remove and use Stdlib instead *) - and module Filename := Base.Filename - and module Format := Base.Format - and module Marshal := Base.Marshal - and module Scanf := Base.Scanf - and type ('ok, 'err) result := ('ok, 'err) Base.result) - [@warning "-3"] + (module type of Base + (* extended below, remove *) + with module Array := Base.Array + and module Invariant := Base.Invariant + and module List := Base.List + and module Map := Base.Map + and module Option := Base.Option + and module Result := Base.Result + and module Set := Base.Set + (* prematurely deprecated, remove and use Stdlib instead *) + and module Filename := Base.Filename + and module Format := Base.Format + and module Marshal := Base.Marshal + and module Scanf := Base.Scanf + and type ('ok, 'err) result := ('ok, 'err) Base.result + [@warning "-3"]) end ) (* undeprecate *) diff --git a/sledge/src/llair/exp.ml b/sledge/src/llair/exp.ml index eff512c30..ea9e53a47 100644 --- a/sledge/src/llair/exp.ml +++ b/sledge/src/llair/exp.ml @@ -342,7 +342,7 @@ module Reg = struct include ( Map : module type of Map - with type ('key, 'value, 'cmp) t := ('key, 'value, 'cmp) Map.t ) + with type ('key, 'value, 'cmp) t := ('key, 'value, 'cmp) Map.t ) type 'v t = 'v Map.M(T).t [@@deriving compare, equal, sexp] diff --git a/sledge/src/llair/term.ml b/sledge/src/llair/term.ml index 27dca5327..a2d7cdb79 100644 --- a/sledge/src/llair/term.ml +++ b/sledge/src/llair/term.ml @@ -318,7 +318,7 @@ module Var = struct include ( Map : module type of Map - with type ('key, 'value, 'cmp) t := ('key, 'value, 'cmp) Map.t ) + with type ('key, 'value, 'cmp) t := ('key, 'value, 'cmp) Map.t ) type 'v t = 'v Map.M(T).t [@@deriving compare, equal, sexp] end diff --git a/sledge/src/llair/typ.mli b/sledge/src/llair/typ.mli index 0473086c1..110073261 100644 --- a/sledge/src/llair/typ.mli +++ b/sledge/src/llair/typ.mli @@ -19,11 +19,7 @@ type t = private | Tuple of {elts: t vector; bits: int; byts: int; packed: bool} (** Anonymous aggregate of heterogeneous types. *) | Struct of - { name: string - ; elts: t vector - ; bits: int - ; byts: int - ; packed: bool } + {name: string; elts: t vector; bits: int; byts: int; packed: bool} (** Uniquely named aggregate of heterogeneous types. Every cycle of recursive types contains a [Struct]. NOTE: recursive [Struct] types are represented by cyclic values. *) diff --git a/sledge/src/sledge_buck.ml b/sledge/src/sledge_buck.ml index e1bcdb0b8..25f0dc37e 100644 --- a/sledge/src/sledge_buck.ml +++ b/sledge/src/sledge_buck.ml @@ -38,9 +38,8 @@ let buck_build ~context target = let open Process in eval ~context (run "buck" - [ "build" - ; "@mode/" ^ Lazy.force mode - ; "-c"; "sledge.build=True"; target ]) + [ "build"; "@mode/" ^ Lazy.force mode; "-c"; "sledge.build=True" + ; target ]) (* split a fully-qualified buck target into file and rule *) let parse_target target = @@ -99,7 +98,7 @@ let expand_arch_archive ~context archive_name = if String.equal is_bc "BC" then ( warn "found bc file %s in %s" name archive_name () ; acc + 1 ) - else acc) ) ) + else acc ) ) ) in number_of_bitcode_files = 0 || fail "found %d bitcode files in archive %s" number_of_bitcode_files diff --git a/sledge/src/symbheap/exec.ml b/sledge/src/symbheap/exec.ml index 1077cd479..e619e7430 100644 --- a/sledge/src/symbheap/exec.ml +++ b/sledge/src/symbheap/exec.ml @@ -234,10 +234,8 @@ let memmov_up_spec us dst src len = {xs; foot; sub= Var.Subst.empty; ms= Var.Set.empty; post} let memmov_specs us dst src len = - [ memmov_eq_spec us dst src len - ; memmov_dj_spec us dst src len - ; memmov_dn_spec us dst src len - ; memmov_up_spec us dst src len ] + [ memmov_eq_spec us dst src len; memmov_dj_spec us dst src len + ; memmov_dn_spec us dst src len; memmov_up_spec us dst src len ] (* { emp } * alloc r [n × l] diff --git a/sledge/src/symbheap/solver.ml b/sledge/src/symbheap/solver.ml index a54d99426..71d789c1c 100644 --- a/sledge/src/symbheap/solver.ml +++ b/sledge/src/symbheap/solver.ml @@ -152,7 +152,8 @@ let excise_seg_sub_prefix ({us; com; min; xs; sub; zs} as goal) msg ssg o_n in let sub = Sh.and_ (Term.eq b b') - (Sh.and_ (Term.eq m m') (Sh.and_ (Term.eq a0 a') (Sh.rem_seg ssg sub))) + (Sh.and_ (Term.eq m m') + (Sh.and_ (Term.eq a0 a') (Sh.rem_seg ssg sub))) in {goal with us; com; min; sub; zs} @@ -235,7 +236,8 @@ let excise_seg_sub_suffix ({us; com; min; xs; sub; zs} as goal) msg ssg l_k in let sub = Sh.and_ (Term.eq b b') - (Sh.and_ (Term.eq m m') (Sh.and_ (Term.eq a1 a') (Sh.rem_seg ssg sub))) + (Sh.and_ (Term.eq m m') + (Sh.and_ (Term.eq a1 a') (Sh.rem_seg ssg sub))) in {goal with us; com; min; sub; zs} @@ -274,8 +276,7 @@ let excise_seg_sub_infix ({us; com; min; xs; sub; zs} as goal) msg ssg l_k (Term.eq (Term.memory ~siz:o ~arr:a) (Term.concat - [| Term.memory ~siz:l_k ~arr:a0 - ; Term.memory ~siz:n ~arr:a1 + [| Term.memory ~siz:l_k ~arr:a0; Term.memory ~siz:n ~arr:a1 ; Term.memory ~siz:ko_ln ~arr:a2 |])) (Sh.star (Sh.seg {loc= k; bas= b; len= m; siz= l_k; arr= a0}) @@ -285,7 +286,8 @@ let excise_seg_sub_infix ({us; com; min; xs; sub; zs} as goal) msg ssg l_k in let sub = Sh.and_ (Term.eq b b') - (Sh.and_ (Term.eq m m') (Sh.and_ (Term.eq a1 a') (Sh.rem_seg ssg sub))) + (Sh.and_ (Term.eq m m') + (Sh.and_ (Term.eq a1 a') (Sh.rem_seg ssg sub))) in {goal with us; com; min; sub; zs} @@ -420,8 +422,7 @@ let excise_seg_min_infix ({us; com; min; xs; sub; zs} as goal) msg ssg k_l (Sh.and_ (Term.eq (Term.concat - [| Term.memory ~siz:k_l ~arr:a0' - ; Term.memory ~siz:o ~arr:a + [| Term.memory ~siz:k_l ~arr:a0'; Term.memory ~siz:o ~arr:a ; Term.memory ~siz:ln_ko ~arr:a2' |]) (Term.memory ~siz:n ~arr:a')) (Sh.star