Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bring better linting #64

Merged
merged 1 commit into from
Sep 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 4 additions & 8 deletions nsiqcppstyle_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ def t_CPPCOMMENT(t):


def t_error(t):
console.Out.Verbose("Illegal character '%s'" % t.value[0], t.lexer.lineno)
console.Out.Verbose(f"Illegal character '{t.value[0]}'", t.lexer.lineno)
t.lexer.skip(1)


Expand Down Expand Up @@ -408,7 +408,7 @@ def __init__(self, filename, data=None):
except UnicodeDecodeError as ex:
console.Out.Ci("[ERROR] UnicodeDecodeError in CppLexerNavigator: " + str(ex))
console.Out.Ci(
"[ERROR] Exception occurred reading file '%s', convert from UTF16LE to UTF8" % (filename),
f"[ERROR] Exception occurred reading file '{filename}', convert from UTF16LE to UTF8",
)
raise
self.lines = self.data.splitlines()
Expand Down Expand Up @@ -922,9 +922,7 @@ def HasBody(self):

if token_id3 is None and token_id2 is not None:
return True
if token_id2 is not None and token_id2.lexpos < token_id3.lexpos:
return True
return False
return bool(token_id2 is not None and token_id2.lexpos < token_id3.lexpos)


class Context:
Expand All @@ -946,9 +944,7 @@ def IsContextEnd(self, token):
return token == self.endToken

def InScope(self, token):
if token.lexpos >= self.startToken.lexpos and token.lexpos <= self.endToken.lexpos:
return True
return False
return bool(token.lexpos >= self.startToken.lexpos and token.lexpos <= self.endToken.lexpos)


class ContextStack:
Expand Down
10 changes: 5 additions & 5 deletions nsiqcppstyle_exe.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ def main():
extLangMapCopy = copy.deepcopy(extLangMap)
targetName = targetPath.name
console.Out.Ci(console.Separator)
console.Out.Ci("= Analyzing %s " % targetName)
console.Out.Ci(f"= Analyzing {targetName} ")

if filterPath != "":
filefilterPath = filterPath
Expand All @@ -281,7 +281,7 @@ def main():
# Load Rule

if len(filter.nsiqCppStyleRules) == 0:
ShowMessageAndExit("Error!. Rules must be set in %s" % filefilterPath, False)
ShowMessageAndExit(f"Error!. Rules must be set in {filefilterPath}", False)
continue

ruleManager.LoadRules(filter.nsiqCppStyleRules)
Expand All @@ -293,7 +293,7 @@ def main():

console.Out.Info(filter.to_string())
console.Out.Ci(console.Separator)
console.Out.Verbose("* run nsiqcppstyle analysis on %s" % targetName)
console.Out.Verbose(f"* run nsiqcppstyle analysis on {targetName}")

# if the target is file, analyze it without condition
if targetPath.is_file():
Expand Down Expand Up @@ -363,7 +363,7 @@ def GetRealTargetPaths(args):
targetPaths.append(realPath)
# CheckPathPermission(realPath, "Target directory")
if not realPath.exists():
ShowMessageAndExit("Error!: Target directory %s does not exist" % eachTarget)
ShowMessageAndExit(f"Error!: Target directory {eachTarget} does not exist")
return targetPaths


Expand Down Expand Up @@ -578,7 +578,7 @@ def AddVarMap(self, keyValuePairString, where):


def GetCliKeyValueMap(kvList):
if kvList == None:
if kvList is None:
return {}

varMap = {}
Expand Down
37 changes: 19 additions & 18 deletions nsiqcppstyle_lexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,11 @@ def clone(self, object=None):
# ------------------------------------------------------------
def _writetab_impl(self, tabfile, tf):
tf.write(f"# {tabfile}.py. This file automatically created by PLY (version {__version__}). Don't edit!\n")
tf.write("_tabversion = %s\n" % repr(__version__))
tf.write("_lextokens = %s\n" % repr(self.lextokens))
tf.write("_lexreflags = %s\n" % repr(self.lexreflags))
tf.write("_lexliterals = %s\n" % repr(self.lexliterals))
tf.write("_lexstateinfo = %s\n" % repr(self.lexstateinfo))
tf.write(f"_tabversion = {__version__!r}\n")
tf.write(f"_lextokens = {self.lextokens!r}\n")
tf.write(f"_lexreflags = {self.lexreflags!r}\n")
tf.write(f"_lexliterals = {self.lexliterals!r}\n")
tf.write(f"_lexstateinfo = {self.lexstateinfo!r}\n")

tabre = {}
# Collect all functions in the initial state
Expand All @@ -207,16 +207,16 @@ def _writetab_impl(self, tabfile, tf):
titem.append((self.lexstateretext[key][i], _funcs_to_names(lre[i][1], self.lexstaterenames[key][i])))
tabre[key] = titem

tf.write("_lexstatere = %s\n" % repr(tabre))
tf.write("_lexstateignore = %s\n" % repr(self.lexstateignore))
tf.write(f"_lexstatere = {tabre!r}\n")
tf.write(f"_lexstateignore = {self.lexstateignore!r}\n")

taberr = {}
for key, ef in self.lexstateerrorf.items():
if ef:
taberr[key] = ef.__name__
else:
taberr[key] = None
tf.write("_lexstateerrorf = %s\n" % repr(taberr))
tf.write(f"_lexstateerrorf = {taberr!r}\n")

# ------------------------------------------------------------
# writetab() - Write lexer information to a table file
Expand All @@ -236,10 +236,10 @@ def readtab(self, tabfile, fdict):
if isinstance(tabfile, types.ModuleType):
lextab = tabfile
elif sys.version_info[0] < 3:
exec("import %s as lextab" % tabfile)
exec(f"import {tabfile} as lextab")
else:
env = {}
exec("import %s as lextab" % tabfile, env, env)
exec(f"import {tabfile} as lextab", env, env)
lextab = env["lextab"]

if getattr(lextab, "_tabversion", "0.0") != __version__:
Expand Down Expand Up @@ -414,7 +414,8 @@ def token(self):
if lexpos == self.lexpos:
# Error method didn't change text position at all. This
# is an error.
raise LexError("Scanning error. Illegal character '%s'" % (lexdata[lexpos]), lexdata[lexpos:])
msg = f"Scanning error. Illegal character '{lexdata[lexpos]}'"
raise LexError(msg, lexdata[lexpos:])
lexpos = self.lexpos
if not newtok:
continue
Expand Down Expand Up @@ -656,7 +657,7 @@ def validate_literals(self):
continue

except TypeError:
self.log.error("Invalid literals specification. literals must be a sequence of characters")
self.log.exception("Invalid literals specification. literals must be a sequence of characters")
self.error = 1

def get_states(self):
Expand All @@ -680,7 +681,7 @@ def get_states(self):
self.log.error("State name %s must be a string", repr(name))
self.error = 1
continue
if not (statetype == "inclusive" or statetype == "exclusive"):
if statetype not in ("inclusive", "exclusive"):
self.log.error("State type for state %s must be 'inclusive' or 'exclusive'", name)
self.error = 1
continue
Expand Down Expand Up @@ -803,9 +804,9 @@ def validate_rules(self):
self.error = 1
except re.error:
_etype, e, _etrace = sys.exc_info()
self.log.error("%s:%d: Invalid regular expression for rule '%s'. %s", file, line, f.__name__, e)
self.log.exception("%s:%d: Invalid regular expression for rule '%s'. %s", file, line, f.__name__, e)
if "#" in f.__doc__:
self.log.error(
self.log.exception(
"%s:%d. Make sure '#' in rule '%s' is escaped with '\\#'",
file,
line,
Expand Down Expand Up @@ -833,9 +834,9 @@ def validate_rules(self):
self.error = 1
except re.error:
_etype, e, _etrace = sys.exc_info()
self.log.error("Invalid regular expression for rule '%s'. %s", name, e)
self.log.exception("Invalid regular expression for rule '%s'. %s", name, e)
if "#" in r:
self.log.error("Make sure '#' in rule '%s' is escaped with '\\#'", name)
self.log.exception("Make sure '#' in rule '%s' is escaped with '\\#'", name)
self.error = 1

if not self.funcsym[state] and not self.strsym[state]:
Expand Down Expand Up @@ -883,7 +884,7 @@ def validate_file(self, filename):
lines = f.readlines()
except UnicodeDecodeError as ex:
console.Out.Ci("[ERROR] UnicodeDecodeError in validate_file: " + str(ex))
console.Out.Ci("[ERROR] Exception occurred reading file '%s', convert from UTF16LE to UTF8" % (filename))
console.Out.Ci(f"[ERROR] Exception occurred reading file '{filename}', convert from UTF16LE to UTF8")
raise
except OSError:
return # Couldn't find the file. Don't worry about it
Expand Down
4 changes: 2 additions & 2 deletions nsiqcppstyle_reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def ReportSummaryToScreen(analyzedFiles, nsiqcppstyle_state, filter):
console.Out.Ci(" ** Total Errors Occurs : %d" % nsiqcppstyle_state.error_count)
console.Out.Ci(" ** Total Analyzed Files : %d" % len(analyzedFiles))
console.Out.Ci(" ** Total Violated Files Count: %d" % violatedFileCount)
console.Out.Ci(" ** Build Quality : %.2f%%" % buildQuality)
console.Out.Ci(f" ** Build Quality : {buildQuality:.2f}%")
if console.IsLevelDisplayed(console.Level.Info):
console.Out.Info("\n================================ Violated Rule Details ===============================")
for checker in nsiqcppstyle_state.errorPerChecker:
Expand Down Expand Up @@ -159,7 +159,7 @@ def EndTarget():

def StartFile(dirname, filename):
if _nsiqcppstyle_state.output_format == "xml":
writer.write("<file name='%s'>\n" % (os.path.join(target, dirname[1:], filename)))
writer.write(f"<file name='{os.path.join(target, dirname[1:], filename)}'>\n")


def EndFile():
Expand Down
9 changes: 3 additions & 6 deletions nsiqcppstyle_rulehelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,8 @@ def GetIndentation(token):

def IsConstructor(value, fullName, context):
"""Check if the passed value is the constructor or destructor"""
if "::" in value and "::" in fullName:
if value == fullName:
return True
if "::" in value and "::" in fullName and value == fullName:
return True
value = value.replace("~", "").split("::")[-1] # remove class and dtor if needed
fullName = fullName.replace("~", "")
names = fullName.split("::")
Expand All @@ -108,6 +107,4 @@ def IsOperator(value):
operator_type = value.removeprefix("operator")
if operator_type == "":
return True
if operator_type[0].isalnum():
return False
return True
return not operator_type[0].isalnum()
2 changes: 1 addition & 1 deletion nsiqcppstyle_rulemanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def LoadRules(self, checkingRuleNames):
for ruleName in checkingRuleNames:
count = self.availRuleNames.count(ruleName)
if count == 0:
console.Out.Error("%s does not exist or incompatible." % ruleName)
console.Out.Error(f"{ruleName} does not exist or incompatible.")
continue
console.Out.Info(" - ", ruleName, "is applied.")
ruleModule = __import__("rules." + ruleName)
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ ignore = [
"PLR0912",
"PLR0913",
"PLR0915",
# Print is used heavily
"T201",
]
unfixable = [
# Don't touch unused imports
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ def RunRule(lexer, contextStack):
unsafe_alternative = True
# elif unknown namespace => unknown safety
if unsafe_alternative:
nsiqcppstyle_reporter.Error(t, __name__, "Do not use bufferoverflow risky function(%s)" % t.value)
nsiqcppstyle_reporter.Error(t, __name__, f"Do not use bufferoverflow risky function({t.value})")
elif not safe_alternative:
nsiqcppstyle_reporter.Error(
t,
__name__,
"Caution: Uknown imlementation of a bufferoverflow risky function(%s)" % t.value,
f"Caution: Uknown imlementation of a bufferoverflow risky function({t.value})",
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def RunRule(lexer, contextStack):
if t2 is not None and t2.type == "LPAREN":
t3 = lexer.PeekPrevTokenSkipWhiteSpaceAndComment()
if t3 is None or t3.type != "PERIOD":
nsiqcppstyle_reporter.Error(t, __name__, "Do not use burfferoverflow risky function(%s)" % t.value)
nsiqcppstyle_reporter.Error(t, __name__, f"Do not use buffer-overflow risky function({t.value})")


ruleManager.AddFunctionScopeRule(RunRule)
Expand Down
2 changes: 1 addition & 1 deletion rules/RULE_3_1_A_do_not_start_filename_with_underbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def RunRule(lexer, filename, dirname):
nsiqcppstyle_reporter.Error(
nsiqcppstyle_reporter.DummyToken(lexer.filename, "", 0, 0),
__name__,
"File name(%s) should not start with underbar." % filename,
f"File name({filename}) should not start with underbar.",
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def RunRule(lexer, filename, dirname):
nsiqcppstyle_reporter.Error(
DummyToken(lexer.filename, "", 0, 0),
__name__,
"Do not use special characters in file name (%s)." % filename,
f"Do not use special characters in file name ({filename}).",
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def RunFileEndRule(lexer, filename, dirname):
nsiqcppstyle_reporter.Error(
DummyToken(lexer.filename, "", 0, 0),
__name__,
"The filename does not represent the classnames (%s)" % (classname),
f"The filename does not represent the classnames ({classname})",
)


Expand Down
2 changes: 1 addition & 1 deletion rules/RULE_3_2_H_do_not_use_underbars_for_cpp_filename.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def RunRule(lexer, filename, dirname):
nsiqcppstyle_reporter.Error(
DummyToken(lexer.filename, "", 0, 0),
__name__,
"Do not use underbar for cpp file name (%s)." % filename,
f"Do not use underbar for cpp file name ({filename}).",
)


Expand Down
2 changes: 1 addition & 1 deletion rules/RULE_3_2_H_do_not_use_uppercase_for_c_filename.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def RunRule(lexer, filename, dirname):
nsiqcppstyle_reporter.Error(
DummyToken(lexer.filename, "", 0, 0),
__name__,
"Do not use uppercase for c file name (%s)." % filename,
f"Do not use uppercase for c file name ({filename}).",
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def RunRule(lexer, fullName, decl, contextStack, context):
nsiqcppstyle_reporter.Error(
t,
__name__,
"The function name(%s) should start with has or is when returinning bool" % fullName,
f"The function name({fullName}) should start with has or is when returinning bool",
)
break
k += 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def RunRule(lexer, fullName, decl, contextStack, context):
return
if IsOperator(value):
return
nsiqcppstyle_reporter.Error(t, __name__, "Do not start function name(%s) with uppercase" % fullName)
nsiqcppstyle_reporter.Error(t, __name__, f"Do not start function name({fullName}) with uppercase")


ruleManager.AddFunctionNameRule(RunRule)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def RunRule(lexer, fullName, decl, contextStack, context):
if value.startswith("~"):
value = value[1:]
if Search("^[a-z]", value) and not IsOperator(value) and t.value not in keywords:
nsiqcppstyle_reporter.Error(t, __name__, "Do not start function name(%s) with lowercase" % fullName)
nsiqcppstyle_reporter.Error(t, __name__, f"Do not start function name({fullName}) with lowercase")


ruleManager.AddFunctionNameRule(RunRule)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def RunRule(lexer, fullName, decl, contextStack, context):
if IsOperator(value):
return
if upperBlock is not None and upperBlock.additional == "PRIVATE" and not value.startswith("_"):
nsiqcppstyle_reporter.Error(t, __name__, "Start private function name(%s) with underbar" % fullName)
nsiqcppstyle_reporter.Error(t, __name__, f"Start private function name({fullName}) with underbar")


def RunTypeScopeRule(lexer, contextStack):
Expand Down
2 changes: 1 addition & 1 deletion rules/RULE_4_1_B_indent_each_enum_item_in_enum_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def RunRule(lexer, typeName, typeFullName, decl, contextStack, typeContext):
nsiqcppstyle_reporter.Error(
t,
__name__,
"Enum block should be indented. But the token(%s) seems to be unindented" % t.value,
f"Enum block should be indented. But the token({t.value}) seems to be unindented",
)


Expand Down
2 changes: 1 addition & 1 deletion rules/RULE_4_1_B_locate_each_enum_item_in_seperate_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def RunRule(lexer, typeName, typeFullName, decl, contextStack, typeContext):
nsiqcppstyle_reporter.Error(
nt2,
__name__,
"Each enum item(%s) should be located in the different line" % nt2.value,
f"Each enum item({nt2.value}) should be located in the different line",
)


Expand Down
Loading
Loading