Annotate getters with @Pure when --java-checkerframework is specified. (#5510)

Together with @Nullable, this allows users to use static analysis tools
like CheckerFramework to catch NPEs caused by unset fields.
This commit is contained in:
jaceksur
2019-09-10 10:01:27 -07:00
committed by Wouter van Oortmerssen
parent 3bfc86eaff
commit 782b865c55
3 changed files with 21 additions and 4 deletions

View File

@@ -228,6 +228,9 @@ class GeneralGenerator : public BaseGenerator {
if (parser_.opts.gen_nullable) {
code += "\nimport javax.annotation.Nullable;\n";
}
if (parser_.opts.java_checkerframework) {
code += "\nimport org.checkerframework.dataflow.qual.Pure;\n";
}
code += lang_.class_annotation;
}
if (parser_.opts.gen_generated) {
@@ -254,6 +257,14 @@ class GeneralGenerator : public BaseGenerator {
: "";
}
std::string GenPureAnnotation(const Type &t) const {
return lang_.language == IDLOptions::kJava &&
parser_.opts.java_checkerframework &&
!IsScalar(DestinationType(t, true).base_type)
? " @Pure "
: "";
}
std::string GenTypeBasic(const Type &type, bool enableLangOverrides) const {
// clang-format off
static const char * const java_typename[] = {
@@ -969,10 +980,11 @@ class GeneralGenerator : public BaseGenerator {
std::string dest_mask = DestinationMask(field.value.type, true);
std::string dest_cast = DestinationCast(field.value.type);
std::string src_cast = SourceCast(field.value.type);
std::string method_start = " public " +
(field.required ? "" : GenNullableAnnotation(field.value.type)) +
type_name_dest + optional + " " +
MakeCamel(field.name, lang_.first_camel_upper);
std::string method_start =
" public " +
(field.required ? "" : GenNullableAnnotation(field.value.type)) +
GenPureAnnotation(field.value.type) + type_name_dest + optional +
" " + MakeCamel(field.name, lang_.first_camel_upper);
std::string obj = lang_.language == IDLOptions::kCSharp
? "(new " + type_name + "())"
: "obj";