Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source
Source file error_code.ml
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480(* Yoann Padioleau
*
* Copyright (C) 2014 Facebook
* Copyright (C) 2019 r2c
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file license.txt.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* license.txt for more details.
*)openCommonmoduleE=Entity_codemodulePI=Parse_info(*****************************************************************************)(* Prelude *)(*****************************************************************************)(* Centralize error management related to errors in user's code
* (as detected by tools such as linters).
*
* history:
* - saw something similar in the code of c--
* - was in check_module.ml
* - was generalized for scheck php
* - introduced ranking via int (but mess)
* - introduced simplified ranking using intermediate rank type
* - fully generalize when introduced graph_code_checker.ml
* - added @Scheck annotation
* - added some false positive deadcode detection
*
* todo:
* - priority to errors, so dead code func more important than dead field
* - factorize code with errors_cpp.ml, errors_php.ml, error_php.ml
*)(*****************************************************************************)(* Globals *)(*****************************************************************************)(* see g_errors below *)(* do not report certain errors.
* Must be used with filter_maybe_parse_and_fatal_errors.
*)letreport_parse_errors=reffalseletreport_fatal_errors=reffalse(*****************************************************************************)(* Types *)(*****************************************************************************)typeerror={typ:error_kind;loc:Parse_info.token_location;sev:severity;}(* less: Advice | Noisy | Meticulous ? *)andseverity=Error|Warninganderror_kind=(* parsing related errors.
* See also try_with_exn_to_errors(), try_with_error_loc_and_reraise(), and
* filter_maybe_parse_and_fatal_errors
*)|LexicalErrorofstring|ParseError(* aka SyntaxError *)|AstbuilderErrorofstring|OtherParsingErrorofstring(* entities *)(* done while building the graph:
* - UndefinedEntity (UseOfUndefined)
* - MultiDefinedEntity (DupeEntity)
*)(* global analysis checker.
* Never done by compilers, and unusual for linters to do that.
*
* note: OCaml 4.01 now does that partially by locally checking if
* an entity is unused and not exported (which does not require a
* global analysis)
*)|Deadcodeofentity|UndefinedDefOfDeclofentity(* really a special case of Deadcode decl *)|UnusedExportofentity(* tge decl*)*Common.filename(* file of def *)(* call sites *)(* should be done by the compiler (ocaml does):
* - TooManyArguments, NotEnoughArguments
* - WrongKeywordArguments
* - ...
*)(* variables *)(* also done by some compilers (ocaml does):
* - UseOfUndefinedVariable
* - UnusedVariable
*)|UnusedVariableofstring*Scope_code.t(* CFG/DFG.
* Again, unreachable statements are rarely checked by compilers or linters,
* but they really should (see https://www.wired.com/2014/02/gotofail/).
* Those are also special cases of Deadcode.
*)|UnusedStatement(* a.k.a UnreachableStatement *)|UnusedAssignofstring|UseOfUninitializedofstring|CFGErrorofstring(* classes *)(* files (include/import) *)(* bail-out constructs *)(* a proper language should not have that *)(* lint *)(* sgrep lint rules *)|SgrepLintof(string(* title/code *)*string(* msg *))(* other *)|FatalErrorofstring(* missing file, OCaml errors, etc. *)(* todo: should be merged with Graph_code.entity or put in Database_code?*)andentity=(string*Entity_code.entity_kind)typerank=(* Too many FPs for now. Not applied even in strict mode. *)|Never(* Usually a few FPs or too many of them. Only applied in strict mode. *)|OnlyStrict|Less|Ok|Important|ReallyImportant(* @xxx to acknowledge or explain false positives *)typeannotation=|AtScheckofstring(* to detect false positives (we use the Hashtbl.find_all property) *)typeidentifier_index=(string,Parse_info.token_location)Hashtbl.t(*****************************************************************************)(* Pretty printers *)(*****************************************************************************)letstring_of_error_kinderror_kind=matcherror_kindwith|Deadcode(s,kind)->spf"dead %s, %s"(Entity_code.string_of_entity_kindkind)s|UndefinedDefOfDecl(s,kind)->spf"no def found for %s (%s)"s(Entity_code.string_of_entity_kindkind)|UnusedExport((s,kind),file_def)->spf"useless export of %s (%s) (consider forward decl in %s)"s(Entity_code.string_of_entity_kindkind)file_def|UnusedVariable(name,scope)->spf"Unused variable %s, scope = %s"name(Scope_code.string_of_scopescope)|SgrepLint(title,message)->spf"%s: %s"titlemessage|UnusedStatement->spf"unreachable statement"|UnusedAssigns->spf"useless assignement for %s; the value in %s is never used after."ss|UseOfUninitializeds->spf"use of unitialized variable: %s"s|LexicalErrors->spf"Lexical error: %s"s|ParseError->"Syntax error"|AstbuilderErrors->spf"AST generation error: %s"s|OtherParsingErrors->spf"Other parsing error: %s"s|CFGErrors->spf"Control flow error: %s"s|FatalErrors->spf"Fatal Error: %s"s(*
let loc_of_node root n g =
try
let info = G.nodeinfo n g in
let pos = info.G.pos in
let file = Filename.concat root pos.PI.file in
spf "%s:%d" file pos.PI.line
with Not_found -> "NO LOCATION"
*)letstring_of_errorerr=letpos=err.locinassert(pos.PI.file<>"");spf"%s:%d:%d: %s"pos.PI.filepos.PI.linepos.PI.column(string_of_error_kinderr.typ)(*****************************************************************************)(* Main entry points *)(*****************************************************************************)letg_errors=ref[]letmk_errortokerr=letloc=PI.token_location_of_infotokin{loc=loc;typ=err;sev=Error}letmk_error_loclocerr={loc=loc;typ=err;sev=Error}leterrortokerr=Common.push(mk_errortokerr)g_errorsletwarningtokerr=letloc=PI.token_location_of_infotokinCommon.push{loc=loc;typ=err;sev=Warning}g_errorsleterror_loclocerr=Common.push(mk_error_loclocerr)g_errorsletwarning_loclocerr=Common.push{loc=loc;typ=err;sev=Warning}g_errors(*****************************************************************************)(* Ranking *)(*****************************************************************************)letscore_of_rank=function|Never->0|OnlyStrict->1|Less->2|Ok->3|Important->4|ReallyImportant->5letrank_of_errorerr=matcherr.typwith|Deadcode(_s,kind)->(matchkindwith|E.Function->Ok(* or enable when use propagate_uses_of_defs_to_decl in graph_code *)|E.GlobalExtern|E.Prototype->Less|_->Ok)(* probably defined in assembly code? *)|UndefinedDefOfDecl_->Important(* we want to simplify interfaces as much as possible! *)|UnusedExport_->ReallyImportant|UnusedVariable_->Less|SgrepLint_->Important|UnusedStatement|UnusedAssign_|UseOfUninitialized_->Important|CFGError_->Important(* usually issues in my parsers *)|LexicalError_|ParseError|AstbuilderError_|OtherParsingError_->OnlyStrict(* usually a bug somewhere in my code *)|FatalError_->OnlyStrictletscore_of_errorerr=err|>rank_of_error|>score_of_rank(*****************************************************************************)(* Error adjustments *)(*****************************************************************************)letoptions()=["-report_parse_errors",Arg.Setreport_parse_errors," report parse errors instead of silencing them";"-report_fatal_errors",Arg.Setreport_fatal_errors," report fatal errors instead of silencing them";]let_is_test_or_examplefile=(file=~".*test.*"||file=~".*spec.*"||file=~".*example.*"||file=~".*bench.*")letfilter_maybe_parse_and_fatal_errorserrs=errs|>Common.exclude(funerr->let_file=err.loc.PI.fileinmatcherr.typwith(*
| LexicalError _ | ParseError
| AstbuilderError _ | OtherParsingError _
| FatalError _
when is_test_or_example file -> true
*)|LexicalError_|ParseError|AstbuilderError_|OtherParsingError_whennot!report_parse_errors->true|FatalError_whennot!report_fatal_errors->true|_->false)letexn_to_errorfileexn=matchexnwith|Parse_info.Lexical_error(s,tok)->mk_errortok(LexicalErrors)|Parse_info.Parsing_errortok->mk_errortok(ParseError);|Parse_info.Ast_builder_error(s,tok)->mk_errortok(AstbuilderErrors);|Parse_info.Other_error(s,tok)->mk_errortok(OtherParsingErrors);(* this should never be captured *)|(Timeout|UnixExit_)asexn->raiseexn(* general case, can't extract line information from it, default to line 1 *)|exn->letloc=Parse_info.first_loc_of_filefileinmk_error_locloc(FatalError(Common.exn_to_sexn))lettry_with_exn_to_errorfilef=tryf()withexn->Common.push(exn_to_errorfileexn)g_errorslettry_with_print_exn_and_reraisefilef=tryf()withexn->letbt=Printexc.get_backtrace()inleterr=exn_to_errorfileexninpr2(string_of_errorerr);pr2bt;(* does not really re-raise :( lose some backtrace *)raiseexnletadjust_paths_relative_to_rootrooterrs=errs|>List.map(fune->letfile=e.loc.PI.fileinletfile'=Common.filename_without_leading_pathrootfilein{ewithloc={e.locwithPI.file=file'}})(* this is for false positives *)letadjust_errorsxs=xs|>Common.exclude(funerr->letfile=err.loc.PI.fileinmatcherr.typwith|Deadcode(s,kind)->(matchkindwith|E.Dir|E.File->true(* kencc *)|E.Prototypewhens="SET"||s="USED"->true(* FP in graph_code_clang for now *)|E.Typewhens=~"E__anon"->true|E.Typewhens=~"U__anon"->true|E.Typewhens=~"S__anon"->true|E.Typewhens=~"E__"->true|E.Typewhens=~"T__"->true(* FP in graph_code_c for now *)|E.Typewhens=~"U____anon"->true(* TODO: to remove, but too many for now *)|E.Constructor|E.Field->true(* hmm plan9 specific? being unused for one project does not mean
* it's not used by another one.
*)|_whenfile=~"^include/"->true|_whenfile=~"^EXTERNAL/"->true(* too many FP on dynamic lang like PHP *)|E.Method->true|_->false)(* kencc *)|UndefinedDefOfDecl(("SET"|"USED"),_)->true|UndefinedDefOfDecl_->(* hmm very plan9 specific *)file=~"^include/"||file="kernel/lib/lib.h"||file="kernel/network/ip/ip.h"||file=~"kernel/conf/"||false|_->false)(*****************************************************************************)(* Annotations *)(*****************************************************************************)letannotation_of_line_opts=ifs=~".*@\\([A-Za-z_]+\\):[ ]?\\([^@]*\\)"thenlet(kind,explain)=Common.matched2sinSome(matchkindwith|"Scheck"->AtScheckexplain|s->failwith("Bad annotation: "^s))elseNone(* The user can override the checks by adding special annotations
* in the code at the same line than the code it related to.
*)letannotation_at2loc=letfile=loc.PI.fileinletline=max(loc.PI.line-1)1inmatchCommon2.cat_excerptsfile[line]with|[s]->annotation_of_line_opts|_->failwith(spf"wrong line number %d in %s"linefile)letannotation_ata=Common.profile_code"Errors_code.annotation"(fun()->annotation_at2a)(*****************************************************************************)(* Helper functions to use in testing code *)(*****************************************************************************)let(expected_error_lines_of_files:Common.filenamelist->(Common.filename*int(* line *))list)=funtest_files->test_files|>List.map(funfile->Common.catfile|>Common.index_list_1|>Common.map_filter(fun(s,idx)->(* Right now we don't care about the actual error messages. We
* don't check if they match. We are just happy to check for
* correct lines error reporting.
*)ifs=~".*ERROR:.*"(* + 1 because the comment is one line before *)thenSome(file,idx+1)elseNone))|>List.flattenletcompare_actual_to_expectedactual_errorsexpected_error_lines=letactual_error_lines=actual_errors|>List.map(funerr->letloc=err.locinloc.PI.file,loc.PI.line)in(* diff report *)let(_common,only_in_expected,only_in_actual)=Common2.diff_set_effexpected_error_linesactual_error_linesinonly_in_expected|>List.iter(fun(src,l)->pr2(spf"this one error is missing: %s:%d"srcl););only_in_actual|>List.iter(fun(src,l)->pr2(spf"this one error was not expected: %s:%d (%s)"srcl(actual_errors|>List.find(funerr->letloc=err.locinsrc=$=loc.PI.file&&l=|=loc.PI.line)|>string_of_error)););OUnit.assert_bool~msg:(spf"it should find all reported errors and no more (%d errors)"(List.length(only_in_actual@only_in_expected)))(nullonly_in_expected&&nullonly_in_actual)