From 40159f52d15f01f08ee8705dce354c8dfd2090d2 Mon Sep 17 00:00:00 2001 From: Brujo Benavides Date: Fri, 21 May 2021 17:04:48 +0200 Subject: [PATCH] Fix #130: Avoid emitting a warning if an attribute is used only where it's defined (#131) --- src/rules/single_use_hrl_attrs.erl | 15 +++++++++++---- .../lib/app/include/header1.hrl | 3 ++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/rules/single_use_hrl_attrs.erl b/src/rules/single_use_hrl_attrs.erl index f00582d..8fab9d3 100644 --- a/src/rules/single_use_hrl_attrs.erl +++ b/src/rules/single_use_hrl_attrs.erl @@ -28,11 +28,11 @@ analyze(FilesAndASTs, _Context) -> [build_macro_result(HrlFile, MacroKey, AttributesUsed) || {HrlFile, #{define := Defines}} <- HrlDefs, MacroKey <- Defines, - is_used_only_once(MacroKey, AttributesUsed)] + is_used_only_once(HrlFile, MacroKey, AttributesUsed)] ++ [build_record_result(HrlFile, RecordKey, AttributesUsed) || {HrlFile, #{record := Records}} <- HrlDefs, RecordKey <- Records, - is_used_only_once(RecordKey, AttributesUsed)]. + is_used_only_once(HrlFile, RecordKey, AttributesUsed)]. build_macro_result(HrlFile, {Macro, Line}, AttributesUsed) -> [File] = maps:get(Macro, AttributesUsed), @@ -56,8 +56,15 @@ build_record_result(HrlFile, {Record, Line}, AttributesUsed) -> text => hank_utils:format_text("#~tp is used only at ~ts", [Record, File]), pattern => Record}. -is_used_only_once({Key, _Line}, AttributesUsed) -> - length(maps:get(Key, AttributesUsed, [])) == 1. +is_used_only_once(HrlFile, {Key, _Line}, AttributesUsed) -> + case maps:get(Key, AttributesUsed, []) of + [SingleFile] -> + %% There is nothing wrong with using an attribute only in the same + %% file where it's defined. + SingleFile /= HrlFile; + _ -> + false + end. file_using({File, FileAST}, CurrentFiles) -> AddFun = fun(Files) -> lists:usort([File | Files]) end, diff --git a/test/files/single_use_hrl_attrs/lib/app/include/header1.hrl b/test/files/single_use_hrl_attrs/lib/app/include/header1.hrl index 6fd6b2c..74410ed 100644 --- a/test/files/single_use_hrl_attrs/lib/app/include/header1.hrl +++ b/test/files/single_use_hrl_attrs/lib/app/include/header1.hrl @@ -1,3 +1,4 @@ -define(APP_HEADER_1, "this is header from app that will be used in just one module"). -define(SOME_MACRO_1(A), A). --define(SOME_DEFINE, ok). +-define(THIS_MACRO, {is_used, "and", it, shouldnt, generate, a, warning}). +-define(SOME_DEFINE, ?THIS_MACRO).