Initial import: the house-style lint rules as a crafter-build module
Moved out of Crafter.Build's lint-rules.h so a project.cpp pulls them in with `#pragma crafter dependency` + `import Crafter.LintRules;` instead of copying a header. The rule bodies are unchanged; format-concat now sits with the other transforms (it rewrites, it was registered as a report), and the helpers are module-internal. tests/HouseRules moved along with the rules and links crafter-build from git, or the sibling checkout with --local. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
commit
88139fc0fc
7 changed files with 2436 additions and 0 deletions
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
bin/
|
||||
build/
|
||||
165
LICENSE
Normal file
165
LICENSE
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
674
LICENSE.GPL
Normal file
674
LICENSE.GPL
Normal file
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program 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
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
60
README.md
Normal file
60
README.md
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
# Crafter.LintRules
|
||||
|
||||
The Catcrafts house-style lint rules for [crafter-build](https://forgejo.catcrafts.net/Catcrafts/Crafter.Build), packaged as one C++ module. Naming conventions, K&R braces, `enum class`, `std::println` over iostream, fixed-width integer types, `std::format` over concatenation, line wrapping, whitespace hygiene and a few AST-backed checks (`const` locals, `constexpr` constants, no `char*`). Most rules are transforms, so `crafter-build format` applies them.
|
||||
|
||||
## Use
|
||||
|
||||
In a `project.cpp`:
|
||||
|
||||
```cpp
|
||||
import std;
|
||||
import Crafter.Build;
|
||||
#pragma crafter dependency "https://forgejo.catcrafts.net/Catcrafts/Crafter.LintRules.git"
|
||||
import Crafter.LintRules;
|
||||
using namespace Crafter;
|
||||
|
||||
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
|
||||
Configuration cfg;
|
||||
// ...
|
||||
LintRules::AddRules(cfg);
|
||||
return cfg;
|
||||
}
|
||||
```
|
||||
|
||||
Then `crafter-build lint` reports, `crafter-build format` rewrites, and `crafter-build format --check` gates CI. Pin a revision for reproducible builds:
|
||||
|
||||
```cpp
|
||||
#pragma crafter dependency "https://forgejo.catcrafts.net/Catcrafts/Crafter.LintRules.git" commit "<sha>"
|
||||
```
|
||||
|
||||
Suppress a finding with `// lint-disable-next-line <rule>` or a whole file with `// lint-disable-file <rule>`.
|
||||
|
||||
## Rules
|
||||
|
||||
| Rule | Kind | What it wants |
|
||||
| --- | --- | --- |
|
||||
| `spdx-header` | report | `// SPDX-License-Identifier:` on line 1, `// SPDX-FileCopyrightText:` on line 2, blank line 3 |
|
||||
| `no-tabs` | report | spaces |
|
||||
| `naming` | report, AST | PascalCase types, functions, statics and constants; camelCase variables |
|
||||
| `enum-class` | report | `enum class`, never a plain `enum` |
|
||||
| `no-iostream-print` | report | `std::println` instead of `std::cout`/`std::cerr` streaming |
|
||||
| `no-char-pointer` | report, AST | `std::string` / `std::string_view` over `char*` outside C interop |
|
||||
| `const-local` | report, AST | `const` on a scalar local that is never written |
|
||||
| `constexpr-constant` | report, AST | `constexpr` on a constant with a constant initialiser |
|
||||
| `format-concat` | transform | `std::format` instead of `+` with string literals |
|
||||
| `fixed-width-types` | transform, AST | `std::int32_t` and friends instead of `int`, `long`, … |
|
||||
| `single-declaration` | transform, AST | one declaration per statement |
|
||||
| `brace-style` | transform | K&R braces |
|
||||
| `if-single-line` | transform | `if (x) return;` on one line when it fits |
|
||||
| `wrap-join` | transform | join wrapped statements that fit on one line |
|
||||
| `paren-spacing` | transform | `if (` and `for (`, no space before a call's `(` |
|
||||
| `trim-trailing-ws` | transform | no trailing whitespace |
|
||||
| `final-newline` | transform | files end with a newline |
|
||||
|
||||
## Tests
|
||||
|
||||
`tests/HouseRules` exercises every rule against small inputs. It links crafter-build to run the linter in-process, so it fetches and builds it from git; with a sibling checkout at `../Crafter.Build` use `crafter-build test --local`.
|
||||
|
||||
## Building for other targets
|
||||
|
||||
The module imports `Crafter.Build`, which only exists for the host. That is all a rule ever needs: rules run inside the crafter-build process that loads your `project.cpp`.
|
||||
982
interfaces/Crafter.LintRules.cppm
Normal file
982
interfaces/Crafter.LintRules.cppm
Normal file
|
|
@ -0,0 +1,982 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.LintRules;
|
||||
import std;
|
||||
import Crafter.Build;
|
||||
|
||||
// The Catcrafts house-style lint rules, as a module for crafter-build. In a
|
||||
// project.cpp:
|
||||
//
|
||||
// #pragma crafter dependency "https://forgejo.catcrafts.net/Catcrafts/Crafter.LintRules.git"
|
||||
// import Crafter.LintRules;
|
||||
// ...
|
||||
// LintRules::AddRules(cfg);
|
||||
//
|
||||
// Deliberately not part of the crafter-build library, so the tool itself
|
||||
// never nudges anyone toward one team's style.
|
||||
//
|
||||
// Report-only rules are registered first so their file:line numbers always
|
||||
// match the on-disk file; transforms run last because each one sees the
|
||||
// previous transform's output, which can shift line numbers.
|
||||
//
|
||||
// All detection runs on ctx.CommentStripped() — comments and string/char
|
||||
// literal bodies are blanked to spaces with newlines preserved, so byte
|
||||
// offsets and line numbers in the stripped text are valid in ctx.content.
|
||||
// Transforms use that property directly: find in stripped, edit in content.
|
||||
|
||||
namespace Crafter::LintRules {
|
||||
|
||||
bool IsCppFile(const Crafter::LintContext& ctx) {
|
||||
std::string ext = ctx.file.extension().string();
|
||||
return ext == ".cpp" || ext == ".cppm" || ext == ".h";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> Lines(std::string_view text) {
|
||||
std::vector<std::string_view> lines;
|
||||
std::size_t start = 0;
|
||||
while (start <= text.size()) {
|
||||
std::size_t end = text.find('\n', start);
|
||||
if (end == std::string_view::npos) {
|
||||
if (start < text.size()) lines.push_back(text.substr(start));
|
||||
break;
|
||||
}
|
||||
lines.push_back(text.substr(start, end - start));
|
||||
start = end + 1;
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
std::string_view Trim(std::string_view s) {
|
||||
while (!s.empty() && (s.front() == ' ' || s.front() == '\t' || s.front() == '\r')) s.remove_prefix(1);
|
||||
while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\r')) s.remove_suffix(1);
|
||||
return s;
|
||||
}
|
||||
|
||||
bool IsWordChar(char c) {
|
||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
|
||||
}
|
||||
|
||||
// Net '(' minus ')' on one stripped line.
|
||||
std::int64_t ParenDelta(std::string_view s) {
|
||||
std::int64_t d = 0;
|
||||
for (char c : s) {
|
||||
if (c == '(') ++d;
|
||||
if (c == ')') --d;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
bool IsPascalCase(std::string_view name) {
|
||||
return !name.empty() && name[0] >= 'A' && name[0] <= 'Z' && !name.contains('_');
|
||||
}
|
||||
|
||||
bool IsCamelCase(std::string_view name) {
|
||||
// One trailing underscore is the member-shadowing-a-keyword convention
|
||||
// (requires_, label_) — allowed.
|
||||
if (name.ends_with('_')) name.remove_suffix(1);
|
||||
return !name.empty() && ((name[0] >= 'a' && name[0] <= 'z') || name[0] == '_') && name.find('_', 1) == std::string_view::npos;
|
||||
}
|
||||
|
||||
// clang spells a pointer type "int *"; house style attaches the star to the
|
||||
// type. Only affects spelling, never which type is meant.
|
||||
std::string NormalisePointerSpelling(std::string_view type) {
|
||||
std::string out;
|
||||
out.reserve(type.size());
|
||||
for (char c : type) {
|
||||
if ((c == '*' || c == '&') && out.ends_with(' ')) out.pop_back();
|
||||
out += c;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// True for a pointer to char, as clang spells a type: "char *",
|
||||
// "const char *", "char **". Deliberately not signed/unsigned char, which are
|
||||
// byte buffers rather than text and were never the target.
|
||||
bool IsCharPointer(std::string_view type) {
|
||||
std::size_t star = type.find('*');
|
||||
if (star == std::string_view::npos) return false;
|
||||
std::string_view base = Trim(type.substr(0, star));
|
||||
if (base.starts_with("const ")) base.remove_prefix(6);
|
||||
if (base.starts_with("volatile ")) base.remove_prefix(9);
|
||||
return base == "char";
|
||||
}
|
||||
}
|
||||
|
||||
export namespace Crafter::LintRules {
|
||||
|
||||
void AddRules(Crafter::Configuration& cfg) {
|
||||
using Crafter::LintContext;
|
||||
|
||||
// ---------------- report-only rules ----------------
|
||||
|
||||
// License header: SPDX identifier on line 1, copyright on line 2, blank
|
||||
// line 3.
|
||||
cfg.AddLintRule("spdx-header", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
if (!ctx.Line(1).starts_with("// SPDX-License-Identifier:")) {
|
||||
ctx.Report(1, "first line must be // SPDX-License-Identifier: ...");
|
||||
}
|
||||
if (!ctx.Line(2).starts_with("// SPDX-FileCopyrightText:")) {
|
||||
ctx.Report(2, "second line must be // SPDX-FileCopyrightText: ...");
|
||||
}
|
||||
if (ctx.lines.size() >= 3 && !Trim(ctx.Line(3)).empty()) {
|
||||
ctx.Report(3, "third line must be blank (separates the license header)");
|
||||
}
|
||||
});
|
||||
|
||||
cfg.AddLintRule("no-tabs", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
for (std::size_t n = 1; n <= ctx.lines.size(); ++n) {
|
||||
if (ctx.Line(n).contains('\t')) ctx.Report(n, "tab character (use spaces)");
|
||||
}
|
||||
});
|
||||
|
||||
// Naming: types and functions PascalCase, variables camelCase, with
|
||||
// statics, namespace-scope globals and constexpr constants PascalCase.
|
||||
//
|
||||
// Reads the AST. The previous version needed four std::regex, a hand-rolled
|
||||
// {/} scope stack, a cumulative paren-depth counter to avoid mistaking a
|
||||
// wrapped parameter list for a declaration, a keyword denylist, and a
|
||||
// "function-shaped line" guess whose own comment conceded it was heuristic.
|
||||
// All of it existed to answer two questions clang answers directly: what
|
||||
// kind of declaration is this, and what encloses it.
|
||||
cfg.AddAstLintRule("naming", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
using Kind = Crafter::LintDeclKind;
|
||||
std::span<const Crafter::LintDecl> decls = ctx.Decls();
|
||||
for (const Crafter::LintDecl& decl : decls) {
|
||||
if (decl.name.empty()) continue; // anonymous namespace, unnamed struct
|
||||
// A declaration with C language linkage is named by the C library
|
||||
// it mirrors — `extern "C" int setenv(...)` is not ours to rename.
|
||||
if (decl.isExternC) continue;
|
||||
// Namespace scope is now a lookup rather than a brace count, and it
|
||||
// is exact for a local declared inside a function body.
|
||||
bool atNamespaceScope = decl.parent == Crafter::LintNoParent
|
||||
|| decls[decl.parent].kind == Kind::Namespace;
|
||||
switch (decl.kind) {
|
||||
case Kind::Class:
|
||||
case Kind::Struct:
|
||||
case Kind::Union:
|
||||
case Kind::Enum:
|
||||
if (!IsPascalCase(decl.name)) {
|
||||
ctx.Report(decl.line, std::format("type '{}' should be PascalCase", decl.name));
|
||||
}
|
||||
break;
|
||||
case Kind::TypeAlias:
|
||||
if (!IsPascalCase(decl.name)) {
|
||||
ctx.Report(decl.line, std::format("type alias '{}' should be PascalCase", decl.name));
|
||||
}
|
||||
break;
|
||||
case Kind::Function:
|
||||
case Kind::Method:
|
||||
// main is spelled by the language; operators by their
|
||||
// symbol. Constructors and destructors take their type's
|
||||
// name and are separate kinds, so they never arrive here.
|
||||
if (decl.name == "main" || decl.name.starts_with("operator")) break;
|
||||
if (!IsPascalCase(decl.name)) {
|
||||
ctx.Report(decl.line, std::format("function '{}' should be PascalCase", decl.name));
|
||||
}
|
||||
break;
|
||||
case Kind::Variable:
|
||||
// constexpr variables are compile-time constants and take
|
||||
// constant naming, like statics and globals.
|
||||
if (decl.isStatic || decl.isConstexpr || atNamespaceScope) {
|
||||
if (!IsPascalCase(decl.name)) {
|
||||
ctx.Report(decl.line, std::format("{} '{}' should be PascalCase",
|
||||
decl.isStatic ? "static variable"
|
||||
: decl.isConstexpr ? "constexpr constant"
|
||||
: "global variable", decl.name));
|
||||
}
|
||||
} else if (!IsCamelCase(decl.name)) {
|
||||
ctx.Report(decl.line, std::format("variable '{}' should be camelCase", decl.name));
|
||||
}
|
||||
break;
|
||||
case Kind::Field:
|
||||
if (decl.isStatic || decl.isConstexpr) {
|
||||
if (!IsPascalCase(decl.name)) {
|
||||
ctx.Report(decl.line, std::format("static member '{}' should be PascalCase", decl.name));
|
||||
}
|
||||
} else if (!IsCamelCase(decl.name)) {
|
||||
ctx.Report(decl.line, std::format("member '{}' should be camelCase", decl.name));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Scoped enums only. Kept on tokens rather than moved to the AST, even
|
||||
// though LintDecl carries an exact isScopedEnum: an AST is one
|
||||
// configuration's slice, so a plain enum inside a preprocessor branch that
|
||||
// is inactive for the host would stop being reported. Tokens are lexed
|
||||
// without evaluating #if, so every platform's code stays covered.
|
||||
cfg.AddLintRule("enum-class", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
std::span<const Crafter::LintToken> tokens = ctx.Tokens();
|
||||
for (std::size_t i = 0; i < tokens.size(); ++i) {
|
||||
if (tokens[i].kind != Crafter::LintTokenKind::Keyword) continue;
|
||||
if (ctx.TokenText(tokens[i]) != "enum") continue;
|
||||
// Asking for the next TOKEN rather than the rest of the line means a
|
||||
// declaration split across lines reads identically to one that is
|
||||
// not — the regex this replaced required the name to follow `enum`
|
||||
// on the same line, so `enum\n Color {` went unreported.
|
||||
std::string_view next = i + 1 < tokens.size() ? ctx.TokenText(tokens[i + 1]) : std::string_view{};
|
||||
if (next == "class" || next == "struct") continue;
|
||||
ctx.Report(tokens[i].line, "use enum class instead of plain enum");
|
||||
}
|
||||
});
|
||||
|
||||
cfg.AddLintRule("no-iostream-print", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
std::vector<std::string_view> lines = Lines(ctx.CommentStripped());
|
||||
for (std::size_t i = 0; i < lines.size(); ++i) {
|
||||
if (lines[i].contains("std::cout")) {
|
||||
ctx.Report(i + 1, "use std::println instead of std::cout");
|
||||
} else if (lines[i].contains("std::cerr") && lines[i].contains("<<")) {
|
||||
ctx.Report(i + 1, "use std::println(std::cerr, ...) instead of streaming to std::cerr");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Prefer std::string / std::string_view over char* in our own declarations.
|
||||
//
|
||||
// Reads the AST rather than the text, which retires the substring denylist
|
||||
// this rule used to carry (argv, getenv, setenv, dlerror, c_str, .data(,
|
||||
// reinterpret_cast, extern "). Every entry was a patch for one interop
|
||||
// site, the list could only grow, and it disabled the rule for a whole LINE
|
||||
// whenever one appeared. The question is now asked directly: whose header
|
||||
// dictates this spelling? A declaration with C language linkage, or one
|
||||
// that binds to an entity declared outside the project, is somebody else's
|
||||
// API and keeps its spelling.
|
||||
//
|
||||
// Only declarations are considered. A char* inside a cast or an expression
|
||||
// is not an interface, and reinterpret_cast<char*> for binary IO — the case
|
||||
// the denylist existed to permit — is no longer a finding to suppress.
|
||||
cfg.AddAstLintRule("no-char-pointer", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
std::span<const Crafter::LintDecl> decls = ctx.Decls();
|
||||
for (const Crafter::LintDecl& decl : decls) {
|
||||
// main's signature is fixed by the language, so its argv is no more
|
||||
// ours to modernise than a C API's is.
|
||||
if (decl.parent != Crafter::LintNoParent && decls[decl.parent].name == "main") continue;
|
||||
if (decl.kind == Crafter::LintDeclKind::Function && decl.name == "main") continue;
|
||||
switch (decl.kind) {
|
||||
case Crafter::LintDeclKind::Variable:
|
||||
case Crafter::LintDeclKind::Parameter:
|
||||
case Crafter::LintDeclKind::Field:
|
||||
case Crafter::LintDeclKind::TypeAlias:
|
||||
case Crafter::LintDeclKind::Function:
|
||||
case Crafter::LintDeclKind::Method:
|
||||
break;
|
||||
default:
|
||||
continue;
|
||||
}
|
||||
if (decl.isExternC || decl.isForeignApi) continue;
|
||||
if (!IsCharPointer(decl.type)) continue;
|
||||
ctx.Report(decl.line, std::format("prefer std::string / std::string_view over char* ('{}' is '{}')", decl.name, decl.type));
|
||||
}
|
||||
});
|
||||
|
||||
// A local that is never written should say so. Restricted to SCALARS —
|
||||
// integers, bools, enums, pointers, floating types — which is what makes
|
||||
// the answer exact rather than a guess: a scalar has no member functions,
|
||||
// so the only ways to write one are assignment, ++/--, having its address
|
||||
// taken, or binding to a non-const reference, and the AST layer tracks all
|
||||
// four. For a class type, a non-const method call could mutate it and
|
||||
// deciding that needs the whole-program analysis clang-tidy does.
|
||||
//
|
||||
// Report-only. Adding const is a judgement about intent as much as
|
||||
// mechanics, and a wrong suggestion should cost a glance, not a build.
|
||||
cfg.AddAstLintRule("const-local", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
std::span<const Crafter::LintDecl> decls = ctx.Decls();
|
||||
for (const Crafter::LintDecl& decl : decls) {
|
||||
if (decl.kind != Crafter::LintDeclKind::Variable) continue;
|
||||
if (decl.parent == Crafter::LintNoParent) continue;
|
||||
// Locals only: a namespace-scope or static variable may be written
|
||||
// from a translation unit this parse cannot see.
|
||||
Crafter::LintDeclKind enclosing = decls[decl.parent].kind;
|
||||
bool isLocal = enclosing == Crafter::LintDeclKind::Function || enclosing == Crafter::LintDeclKind::Method
|
||||
|| enclosing == Crafter::LintDeclKind::Constructor || enclosing == Crafter::LintDeclKind::Destructor;
|
||||
if (!isLocal || decl.isStatic) continue;
|
||||
if (decl.isConst || decl.isConstexpr) continue;
|
||||
if (!decl.isScalar || decl.isMutated) continue;
|
||||
if (decl.name.empty()) continue;
|
||||
// A range-for binding is not what a reader pictures as an
|
||||
// assignable variable, and `for (T* const x : …)` is not a spelling
|
||||
// anybody writes.
|
||||
if (decl.isLoopVariable) continue;
|
||||
// Likewise `T* const p` — the useful constness for a pointer local
|
||||
// is almost always on the pointee, which this rule cannot advise
|
||||
// on. Restricting to value types keeps the advice actionable.
|
||||
if (decl.type.contains('*')) continue;
|
||||
ctx.Report(decl.line, std::format("'{}' is never modified — declare it const", decl.name));
|
||||
}
|
||||
});
|
||||
|
||||
// A constant whose value is already a constant expression can be constexpr,
|
||||
// which moves it into the type system instead of leaving it to the
|
||||
// optimiser. Constant-ness of the initialiser is decided by clang's own
|
||||
// evaluator, so `sizeof(T)`, a fold over other constants and anything else
|
||||
// that folds all qualify, while `Compute()` does not.
|
||||
//
|
||||
// Restricted to scalars on purpose: for a class type, constexpr may be
|
||||
// unavailable even when the initialiser folds (a std::string constant
|
||||
// cannot be constexpr at namespace scope), and the evaluator answering
|
||||
// "this folds" is not the same question as "constexpr is legal here".
|
||||
cfg.AddAstLintRule("constexpr-constant", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
for (const Crafter::LintDecl& decl : ctx.Decls()) {
|
||||
if (decl.kind != Crafter::LintDeclKind::Variable && decl.kind != Crafter::LintDeclKind::Field) continue;
|
||||
if (!decl.isConst || decl.isConstexpr || !decl.isScalar) continue;
|
||||
// A pointer's value is an address, which is rarely a constant
|
||||
// expression and never an interesting one to promote.
|
||||
if (decl.type.contains('*')) continue;
|
||||
if (!decl.isConstantInitialised) continue;
|
||||
if (decl.name.empty()) continue;
|
||||
ctx.Report(decl.line, std::format("'{}' has a constant initialiser — declare it constexpr", decl.name));
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------- transforms (auto-fixed by `crafter-build format`) ----------------
|
||||
|
||||
// String building via `+` with a literal operand → std::format. Plain
|
||||
// `a += b` accumulation (builder pattern) stays legal. Single-line chains
|
||||
// of simple operands (identifier / member / call chains, parenthesized
|
||||
// groups, literals) are REWRITTEN automatically; anything the operand
|
||||
// scanner can't prove safe — raw-string lines, ternaries, mixed
|
||||
// operators, multi-line expressions — is reported for a human instead.
|
||||
cfg.AddLintRule("format-concat", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
const std::string& code = ctx.CommentStripped();
|
||||
std::vector<std::string_view> stripped = Lines(code);
|
||||
|
||||
// Walk one operand leftwards from `from` (exclusive). Returns the
|
||||
// operand's begin, or npos when the shape isn't a simple postfix
|
||||
// chain (then the whole chain bails to a report).
|
||||
auto operandLeft = [](std::string_view s, std::size_t from) -> std::size_t {
|
||||
std::size_t i = from;
|
||||
while (i > 0 && (s[i - 1] == ' ' || s[i - 1] == '\t')) --i;
|
||||
bool any = false;
|
||||
for (;;) {
|
||||
if (i == 0) break;
|
||||
char c = s[i - 1];
|
||||
if (c == ')' || c == ']') {
|
||||
char open = c == ')' ? '(' : '[';
|
||||
std::size_t depth = 0;
|
||||
do {
|
||||
--i;
|
||||
if (s[i] == c) ++depth;
|
||||
if (s[i] == open) --depth;
|
||||
if (depth == 0) break;
|
||||
} while (i > 0);
|
||||
if (depth != 0) return std::string_view::npos;
|
||||
any = true;
|
||||
// A group directly preceded by an identifier (or another
|
||||
// group) is a call/index postfix — keep consuming the
|
||||
// callee: `path.string()` is ONE operand, not `()`.
|
||||
if (i > 0 && (IsWordChar(s[i - 1]) || s[i - 1] == ')' || s[i - 1] == ']')) continue;
|
||||
} else if (c == '"') {
|
||||
--i; // closing quote; interior is blanked, find the opener
|
||||
while (i > 0 && s[i - 1] != '"') --i;
|
||||
if (i == 0) return std::string_view::npos;
|
||||
--i;
|
||||
any = true;
|
||||
} else if (IsWordChar(c)) {
|
||||
while (i > 0 && IsWordChar(s[i - 1])) --i;
|
||||
any = true;
|
||||
} else if (c == '.' && any) {
|
||||
--i;
|
||||
continue;
|
||||
} else if (c == ':' && i > 1 && s[i - 2] == ':' && any) {
|
||||
i -= 2;
|
||||
continue;
|
||||
} else if (c == '>' && i > 1 && s[i - 2] == '-' && any) {
|
||||
i -= 2;
|
||||
continue;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
// After a primary, only connectors continue the operand.
|
||||
if (i > 0 && (s[i - 1] == '.' || (s[i - 1] == ':' && i > 1 && s[i - 2] == ':')
|
||||
|| (s[i - 1] == '>' && i > 1 && s[i - 2] == '-'))) continue;
|
||||
break;
|
||||
}
|
||||
if (!any) return std::string_view::npos;
|
||||
// A unary operator, ternary, or other-precedence operator in
|
||||
// front means expression structure we don't reason about — bail.
|
||||
std::size_t b = i;
|
||||
while (b > 0 && (s[b - 1] == ' ' || s[b - 1] == '\t')) --b;
|
||||
if (b > 0 && std::string_view("!*&~-?:<>/%^|").contains(s[b - 1])) return std::string_view::npos;
|
||||
return i;
|
||||
};
|
||||
|
||||
// Walk one operand rightwards from `from` (inclusive). Returns one
|
||||
// past the operand's end, or npos on bail.
|
||||
auto operandRight = [](std::string_view s, std::size_t from) -> std::size_t {
|
||||
std::size_t i = from;
|
||||
while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;
|
||||
bool any = false;
|
||||
for (;;) {
|
||||
if (i >= s.size()) break;
|
||||
char c = s[i];
|
||||
if (c == '(' || c == '[') {
|
||||
char close = c == '(' ? ')' : ']';
|
||||
std::size_t depth = 0;
|
||||
while (i < s.size()) {
|
||||
if (s[i] == c) ++depth;
|
||||
if (s[i] == close && --depth == 0) { ++i; break; }
|
||||
++i;
|
||||
}
|
||||
if (depth != 0) return std::string_view::npos;
|
||||
any = true;
|
||||
} else if (c == '"') {
|
||||
++i;
|
||||
while (i < s.size() && s[i] != '"') ++i;
|
||||
if (i >= s.size()) return std::string_view::npos;
|
||||
++i;
|
||||
any = true;
|
||||
} else if (IsWordChar(c)) {
|
||||
while (i < s.size() && IsWordChar(s[i])) ++i;
|
||||
any = true;
|
||||
} else if (any && c == '.') {
|
||||
++i;
|
||||
continue;
|
||||
} else if (any && c == ':' && i + 1 < s.size() && s[i + 1] == ':') {
|
||||
i += 2;
|
||||
continue;
|
||||
} else if (any && c == '-' && i + 1 < s.size() && s[i + 1] == '>') {
|
||||
i += 2;
|
||||
continue;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
if (i < s.size() && (s[i] == '(' || s[i] == '[' || s[i] == '.'
|
||||
|| (s[i] == ':' && i + 1 < s.size() && s[i + 1] == ':')
|
||||
|| (s[i] == '-' && i + 1 < s.size() && s[i + 1] == '>'))) continue;
|
||||
break;
|
||||
}
|
||||
return any ? i : std::string_view::npos;
|
||||
};
|
||||
|
||||
struct Edit { std::size_t begin; std::size_t end; std::string replacement; };
|
||||
std::vector<Edit> edits; // offsets into ctx.content
|
||||
std::size_t lineStart = 0;
|
||||
for (std::size_t li = 0; li < stripped.size(); ++li) {
|
||||
std::string_view line = stripped[li];
|
||||
std::size_t lineOff = lineStart;
|
||||
lineStart += line.size() + 1;
|
||||
std::string_view trimmed = Trim(line);
|
||||
if (trimmed.starts_with('#')) continue;
|
||||
// A chain is read within one line, so a literal that spans lines
|
||||
// would be sliced in half by chainEnd. Single-line raw strings are
|
||||
// fine: they reduce to R"…" in the stripped view, so they fail the
|
||||
// "is a plain literal" test below and travel through as an
|
||||
// argument, spelling and all.
|
||||
bool spansLines = ctx.LineHasMultiLineToken(li + 1);
|
||||
|
||||
std::size_t searchFrom = 0;
|
||||
while (searchFrom < line.size()) {
|
||||
// A candidate `+` that isn't ++ / += and touches a literal.
|
||||
std::size_t plus = line.find('+', searchFrom);
|
||||
if (plus == std::string_view::npos) break;
|
||||
searchFrom = plus + 1;
|
||||
if (plus + 1 < line.size() && (line[plus + 1] == '+' || line[plus + 1] == '=')) { ++searchFrom; continue; }
|
||||
if (plus > 0 && line[plus - 1] == '+') continue;
|
||||
std::size_t leftEnd = plus;
|
||||
while (leftEnd > 0 && (line[leftEnd - 1] == ' ' || line[leftEnd - 1] == '\t')) --leftEnd;
|
||||
std::size_t rightBegin = plus + 1;
|
||||
while (rightBegin < line.size() && (line[rightBegin] == ' ' || line[rightBegin] == '\t')) ++rightBegin;
|
||||
bool literalAdjacent = (leftEnd > 0 && line[leftEnd - 1] == '"')
|
||||
|| (rightBegin < line.size() && line[rightBegin] == '"');
|
||||
if (!literalAdjacent) continue;
|
||||
if (spansLines) {
|
||||
ctx.Report(li + 1, "use std::format instead of string concatenation with + (multi-line literal, fix manually)");
|
||||
break;
|
||||
}
|
||||
|
||||
// Expand to the full chain: operands joined by `+`.
|
||||
std::size_t chainBegin = operandLeft(line, plus);
|
||||
std::size_t chainEnd = operandRight(line, plus + 1);
|
||||
bool bail = chainBegin == std::string_view::npos || chainEnd == std::string_view::npos;
|
||||
while (!bail) {
|
||||
std::size_t b = chainBegin;
|
||||
while (b > 0 && (line[b - 1] == ' ' || line[b - 1] == '\t')) --b;
|
||||
if (b > 0 && line[b - 1] == '+' && !(b > 1 && line[b - 2] == '+')) {
|
||||
std::size_t prev = operandLeft(line, b - 1);
|
||||
if (prev == std::string_view::npos) { bail = true; break; }
|
||||
chainBegin = prev;
|
||||
} else break;
|
||||
}
|
||||
while (!bail) {
|
||||
std::size_t e = chainEnd;
|
||||
while (e < line.size() && (line[e] == ' ' || line[e] == '\t')) ++e;
|
||||
if (e < line.size() && line[e] == '+' && !(e + 1 < line.size() && (line[e + 1] == '+' || line[e + 1] == '='))) {
|
||||
std::size_t next = operandRight(line, e + 1);
|
||||
if (next == std::string_view::npos) { bail = true; break; }
|
||||
chainEnd = next;
|
||||
} else break;
|
||||
}
|
||||
if (bail) {
|
||||
ctx.Report(li + 1, "use std::format instead of string concatenation with + (not auto-fixable)");
|
||||
break;
|
||||
}
|
||||
|
||||
// Split the chain at depth-0 '+' into parts; literals feed the
|
||||
// format string, everything else becomes an argument.
|
||||
std::string_view chain = line.substr(chainBegin, chainEnd - chainBegin);
|
||||
std::string_view rawChain = std::string_view(ctx.content).substr(lineOff + chainBegin, chainEnd - chainBegin);
|
||||
std::string fmt;
|
||||
std::vector<std::string_view> args;
|
||||
std::size_t partBegin = 0;
|
||||
std::int64_t depth = 0;
|
||||
bool inLit = false;
|
||||
for (std::size_t p = 0; p <= chain.size(); ++p) {
|
||||
if (p < chain.size()) {
|
||||
char c = chain[p];
|
||||
if (c == '"') inLit = !inLit;
|
||||
if (inLit) continue;
|
||||
if (c == '(' || c == '[') ++depth;
|
||||
if (c == ')' || c == ']') --depth;
|
||||
if (!(c == '+' && depth == 0)) continue;
|
||||
}
|
||||
std::string_view part = Trim(chain.substr(partBegin, p - partBegin));
|
||||
std::string_view rawPart = Trim(rawChain.substr(partBegin, p - partBegin));
|
||||
if (part.starts_with('"') && part.ends_with('"') && part.size() >= 2
|
||||
&& std::count(part.begin(), part.end(), '"') == 2) {
|
||||
for (char c : rawPart.substr(1, rawPart.size() - 2)) {
|
||||
fmt += c;
|
||||
if (c == '{') fmt += '{';
|
||||
if (c == '}') fmt += '}';
|
||||
}
|
||||
} else if (part.contains('"') && part.contains('+')) {
|
||||
bail = true; // nested concat inside an operand — human territory
|
||||
break;
|
||||
} else {
|
||||
fmt += "{}";
|
||||
args.push_back(rawPart);
|
||||
}
|
||||
partBegin = p + 1;
|
||||
}
|
||||
if (bail || args.empty()) {
|
||||
ctx.Report(li + 1, "use std::format instead of string concatenation with + (not auto-fixable)");
|
||||
break;
|
||||
}
|
||||
std::string replacement = std::format("std::format(\"{}\"", fmt);
|
||||
for (std::string_view a : args) replacement += std::format(", {}", a);
|
||||
replacement += ")";
|
||||
edits.push_back({lineOff + chainBegin, lineOff + chainEnd, std::move(replacement)});
|
||||
searchFrom = chainEnd;
|
||||
}
|
||||
}
|
||||
if (edits.empty()) return;
|
||||
std::string out = ctx.content;
|
||||
std::sort(edits.begin(), edits.end(), [](const Edit& a, const Edit& b) { return a.begin > b.begin; });
|
||||
for (const Edit& e : edits) out.replace(e.begin, e.end - e.begin, e.replacement);
|
||||
ctx.SetContent(std::move(out));
|
||||
});
|
||||
|
||||
// short/int/long → fixed-width types. Lines mentioning main/argc/argv or
|
||||
// extern "C" keep their C-conventional ints.
|
||||
cfg.AddAstLintRule("fixed-width-types", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
const std::string& code = ctx.CommentStripped();
|
||||
struct Rep { std::size_t pos; std::size_t len; std::string to; };
|
||||
std::vector<Rep> reps;
|
||||
|
||||
// Byte ranges whose integer spelling is not ours to change. A wrong
|
||||
// rewrite here does not merely over-report — it produces code that no
|
||||
// longer matches the API it is calling — so this is derived from the
|
||||
// AST rather than from substrings on the line.
|
||||
//
|
||||
// Replaces the old per-LINE textual exemption (`int main`, `argc`,
|
||||
// `argv`, `extern "`), which both missed cases and disabled the rule
|
||||
// for everything else sharing a line with one of those words.
|
||||
std::vector<std::pair<std::size_t, std::size_t>> protectedRanges;
|
||||
for (const Crafter::LintDecl& decl : ctx.Decls()) {
|
||||
if (decl.isExternC || decl.isForeignApi) {
|
||||
protectedRanges.emplace_back(decl.begin, decl.end);
|
||||
continue;
|
||||
}
|
||||
// main's signature is fixed by the language. Only the signature:
|
||||
// its body is ordinary code, and the declaration's extent covers
|
||||
// the whole function.
|
||||
if (decl.kind == Crafter::LintDeclKind::Function && decl.name == "main") {
|
||||
std::size_t bodyBrace = ctx.content.find('{', decl.begin);
|
||||
protectedRanges.emplace_back(decl.begin, bodyBrace == std::string::npos ? decl.end : bodyBrace);
|
||||
}
|
||||
}
|
||||
auto isProtected = [&protectedRanges](std::size_t offset) {
|
||||
return std::any_of(protectedRanges.begin(), protectedRanges.end(),
|
||||
[offset](const std::pair<std::size_t, std::size_t>& range) {
|
||||
return offset >= range.first && offset < range.second;
|
||||
});
|
||||
};
|
||||
// Builtin integer type specifiers combine in any order (`unsigned
|
||||
// long`, `long unsigned int`, ...), so match whole RUNS of these
|
||||
// keywords and classify the run, rather than the words one by one.
|
||||
static const std::unordered_set<std::string_view> IntWords = {
|
||||
"unsigned", "signed", "short", "long", "int", "char",
|
||||
};
|
||||
std::size_t lineStart = 0;
|
||||
while (lineStart <= code.size()) {
|
||||
std::size_t lineEnd = code.find('\n', lineStart);
|
||||
if (lineEnd == std::string::npos) lineEnd = code.size();
|
||||
std::string_view line(code.data() + lineStart, lineEnd - lineStart);
|
||||
std::size_t pos = 0;
|
||||
while (pos < line.size()) {
|
||||
if (!IsWordChar(line[pos])) { ++pos; continue; }
|
||||
std::size_t wordEnd = pos;
|
||||
while (wordEnd < line.size() && IsWordChar(line[wordEnd])) ++wordEnd;
|
||||
if (!IntWords.contains(line.substr(pos, wordEnd - pos))) { pos = wordEnd; continue; }
|
||||
|
||||
// Extend the run over consecutive specifier keywords.
|
||||
std::size_t runBegin = pos;
|
||||
std::size_t runEnd = wordEnd;
|
||||
bool hasUnsigned = false;
|
||||
bool hasSigned = false;
|
||||
bool hasShort = false;
|
||||
bool hasChar = false;
|
||||
bool hasLong = false;
|
||||
std::string_view nextWord;
|
||||
for (;;) {
|
||||
std::string_view word = line.substr(pos, wordEnd - pos);
|
||||
if (word == "unsigned") hasUnsigned = true;
|
||||
else if (word == "signed") hasSigned = true;
|
||||
else if (word == "short") hasShort = true;
|
||||
else if (word == "char") hasChar = true;
|
||||
else if (word == "long") hasLong = true;
|
||||
runEnd = wordEnd;
|
||||
pos = wordEnd;
|
||||
while (pos < line.size() && (line[pos] == ' ' || line[pos] == '\t')) ++pos;
|
||||
wordEnd = pos;
|
||||
while (wordEnd < line.size() && IsWordChar(line[wordEnd])) ++wordEnd;
|
||||
nextWord = line.substr(pos, wordEnd - pos);
|
||||
if (!IntWords.contains(nextWord)) break;
|
||||
}
|
||||
pos = runEnd;
|
||||
|
||||
// Bare `char` is text, not an integer — only signed/unsigned
|
||||
// char is byte arithmetic. `long double` is a floating type.
|
||||
if (hasChar && !hasUnsigned && !hasSigned) continue;
|
||||
if (nextWord == "double") continue;
|
||||
|
||||
if (isProtected(lineStart + runBegin)) continue;
|
||||
|
||||
std::string_view width = hasChar ? "8" : hasShort ? "16" : hasLong ? "64" : "32";
|
||||
reps.push_back({lineStart + runBegin, runEnd - runBegin,
|
||||
std::format("std::{}int{}_t", hasUnsigned ? "u" : "", width)});
|
||||
}
|
||||
lineStart = lineEnd + 1;
|
||||
}
|
||||
if (reps.empty()) return;
|
||||
std::string out = ctx.content;
|
||||
std::sort(reps.begin(), reps.end(), [](const Rep& a, const Rep& b) { return a.pos > b.pos; });
|
||||
for (const Rep& r : reps) out.replace(r.pos, r.len, r.to);
|
||||
ctx.SetContent(std::move(out));
|
||||
});
|
||||
|
||||
// One declaration per statement. Auto-splits the simple initialized form
|
||||
// `Type a = x, b = y;`; anything with pointers/references, parens, or
|
||||
// templates in the declarators is only reported (splitting `int* a, b;`
|
||||
// would change b's type).
|
||||
cfg.AddAstLintRule("single-declaration", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
std::span<const Crafter::LintDecl> decls = ctx.Decls();
|
||||
std::span<const Crafter::LintToken> tokens = ctx.Tokens();
|
||||
|
||||
struct Edit { std::size_t begin; std::size_t end; std::string text; };
|
||||
std::vector<Edit> edits;
|
||||
|
||||
for (std::size_t i = 0; i < decls.size(); ++i) {
|
||||
const Crafter::LintDecl& head = decls[i];
|
||||
if (head.kind != Crafter::LintDeclKind::Variable && head.kind != Crafter::LintDeclKind::Field) continue;
|
||||
// A group head owns the shared type, so its extent starts before
|
||||
// its name. Continuation declarators start AT their name.
|
||||
if (head.begin == head.nameOffset) continue;
|
||||
|
||||
std::size_t last = i;
|
||||
while (last + 1 < decls.size()) {
|
||||
const Crafter::LintDecl& next = decls[last + 1];
|
||||
if (next.kind != head.kind || next.parent != head.parent) break;
|
||||
if (next.begin != next.nameOffset) break; // starts a new statement
|
||||
++last;
|
||||
}
|
||||
if (last == i) continue; // a single declarator: nothing to split
|
||||
|
||||
// The statement runs to the ';' after the final declarator.
|
||||
auto semicolon = std::ranges::find_if(tokens, [&](const Crafter::LintToken& t) {
|
||||
return t.offset >= decls[last].end && ctx.TokenText(t) == ";";
|
||||
});
|
||||
if (semicolon == tokens.end()) continue;
|
||||
std::size_t stmtEnd = semicolon->offset + 1;
|
||||
|
||||
// A comment anywhere inside the statement would be swallowed by the
|
||||
// rewrite. One AFTER the ';' is outside the replaced range and
|
||||
// survives, which the line-based version could not manage — it
|
||||
// refused the whole line.
|
||||
bool hasInnerComment = std::ranges::any_of(tokens, [&](const Crafter::LintToken& t) {
|
||||
return t.kind == Crafter::LintTokenKind::Comment && t.offset >= head.begin && t.offset < stmtEnd;
|
||||
});
|
||||
if (hasInnerComment) continue;
|
||||
if (ctx.Suppressed("single-declaration", head.line)) continue;
|
||||
|
||||
// Indent from the head's own line, so a statement that starts
|
||||
// mid-line is left alone rather than reflowed.
|
||||
std::size_t lineBegin = ctx.content.rfind('\n', head.begin);
|
||||
lineBegin = lineBegin == std::string::npos ? 0 : lineBegin + 1;
|
||||
if (!Trim(std::string_view(ctx.content).substr(lineBegin, head.begin - lineBegin)).empty()) continue;
|
||||
std::string indent(std::string_view(ctx.content).substr(lineBegin, head.begin - lineBegin));
|
||||
|
||||
std::string replacement;
|
||||
for (std::size_t d = i; d <= last; ++d) {
|
||||
// Each declarator gets its OWN type. This is the whole reason
|
||||
// this rule needed the AST: copying the head's type prefix
|
||||
// turns `int* a, b;` into `int* a; int* b;` and silently
|
||||
// changes b's type. clang has already resolved b as plain int.
|
||||
std::string type = NormalisePointerSpelling(decls[d].type);
|
||||
std::string_view declarator = std::string_view(ctx.content).substr(decls[d].nameOffset, decls[d].end - decls[d].nameOffset);
|
||||
if (d > i) replacement += std::format("\n{}", indent);
|
||||
// NormalisePointerSpelling already attached the star to the
|
||||
// type, so the separator is always a single space: `int* a`.
|
||||
replacement += std::format("{} {};", type, Trim(declarator));
|
||||
}
|
||||
edits.push_back({head.begin, stmtEnd, std::move(replacement)});
|
||||
i = last;
|
||||
}
|
||||
|
||||
if (edits.empty()) return;
|
||||
std::string out = ctx.content;
|
||||
std::ranges::sort(edits, [](const Edit& a, const Edit& b) { return a.begin > b.begin; });
|
||||
for (const Edit& e : edits) out.replace(e.begin, e.end - e.begin, e.text);
|
||||
ctx.SetContent(std::move(out));
|
||||
});
|
||||
|
||||
// K&R braces: `{` on its own line after a `)`/else/do/try header joins
|
||||
// onto the header line. Standalone scope blocks (previous line ends with
|
||||
// `;`, `{`, a comment, …) are intentional and stay.
|
||||
cfg.AddLintRule("brace-style", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
std::vector<std::string_view> stripped = Lines(ctx.CommentStripped());
|
||||
std::vector<std::string> outLines;
|
||||
outLines.reserve(ctx.lines.size());
|
||||
bool changed = false;
|
||||
for (std::size_t i = 0; i < ctx.lines.size(); ++i) {
|
||||
std::string_view trimmed = Trim(stripped[i]);
|
||||
if (trimmed == "{" && !outLines.empty()) {
|
||||
std::string_view prevTrim = i > 0 ? Trim(stripped[i - 1]) : std::string_view{};
|
||||
bool headerBefore = prevTrim.ends_with(')') || prevTrim == "else" || prevTrim == "do" || prevTrim == "try";
|
||||
bool hasComment = ctx.LineHasComment(i + 1) || (i > 0 && ctx.LineHasComment(i));
|
||||
bool suppressed = ctx.Suppressed("brace-style", i) || ctx.Suppressed("brace-style", i + 1);
|
||||
if (headerBefore && !hasComment && !suppressed) {
|
||||
std::string& prev = outLines.back();
|
||||
while (!prev.empty() && (prev.back() == ' ' || prev.back() == '\t')) prev.pop_back();
|
||||
prev += " {";
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
outLines.emplace_back(ctx.Line(i + 1));
|
||||
}
|
||||
if (!changed) return;
|
||||
std::string out;
|
||||
for (std::size_t i = 0; i < outLines.size(); ++i) {
|
||||
out += outLines[i];
|
||||
if (i + 1 < outLines.size() || ctx.content.ends_with('\n')) out += '\n';
|
||||
}
|
||||
ctx.SetContent(std::move(out));
|
||||
});
|
||||
|
||||
// Single-statement if bodies join onto the if line: `if (x)\n y;` →
|
||||
// `if (x) y;` — when the condition's parens balance on one line, the body
|
||||
// is one `;`-terminated statement, neither line carries a comment, and
|
||||
// the joined line stays ≤ 250 columns.
|
||||
cfg.AddLintRule("if-single-line", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
std::vector<std::string_view> stripped = Lines(ctx.CommentStripped());
|
||||
static const std::regex ifHeader(R"(^\s*(?:\}?\s*else\s+)?if\s*\(.*\)\s*$)");
|
||||
std::vector<std::string> outLines;
|
||||
bool changed = false;
|
||||
for (std::size_t i = 0; i < ctx.lines.size(); ++i) {
|
||||
std::string lineStr(stripped[i]);
|
||||
if (i + 1 < ctx.lines.size() && std::regex_match(lineStr, ifHeader) && ParenDelta(stripped[i]) == 0) {
|
||||
std::string_view body = Trim(stripped[i + 1]);
|
||||
bool joinable = !body.empty() && body != "{" && !body.starts_with("if") && body.ends_with(';')
|
||||
&& !ctx.LineHasComment(i + 1) && !ctx.LineHasComment(i + 2)
|
||||
&& !ctx.Suppressed("if-single-line", i + 1) && !ctx.Suppressed("if-single-line", i + 2);
|
||||
std::string joined = std::string(ctx.Line(i + 1));
|
||||
while (!joined.empty() && (joined.back() == ' ' || joined.back() == '\t')) joined.pop_back();
|
||||
joined += " ";
|
||||
joined += Trim(ctx.Line(i + 2));
|
||||
if (joinable && joined.size() <= 250) {
|
||||
outLines.push_back(std::move(joined));
|
||||
++i; // consume the body line
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
outLines.emplace_back(ctx.Line(i + 1));
|
||||
}
|
||||
if (!changed) return;
|
||||
std::string out;
|
||||
for (std::size_t i = 0; i < outLines.size(); ++i) {
|
||||
out += outLines[i];
|
||||
if (i + 1 < outLines.size() || ctx.content.ends_with('\n')) out += '\n';
|
||||
}
|
||||
ctx.SetContent(std::move(out));
|
||||
});
|
||||
|
||||
// Wrapped call arguments join back onto one line when the whole
|
||||
// expression fits in 250 columns. Lambda bodies (lines ending `{`),
|
||||
// comments, raw strings, and preprocessor lines are left alone.
|
||||
// Operator-style continuations (next line starts with && / || / |) join
|
||||
// under the same length limit.
|
||||
cfg.AddLintRule("wrap-join", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
// Fixpoint loop: a join can enable another (joining an inner paren
|
||||
// wrap balances the line an operator continuation hangs off), so one
|
||||
// pass is not idempotent. Iterate until a pass changes nothing; the
|
||||
// cap is a safety net — joins strictly reduce the line count, so
|
||||
// termination is guaranteed anyway.
|
||||
for (std::int32_t pass = 0; pass < 16; ++pass) {
|
||||
std::vector<std::string_view> stripped = Lines(ctx.CommentStripped());
|
||||
std::vector<std::string> outLines;
|
||||
bool changed = false;
|
||||
for (std::size_t i = 0; i < ctx.lines.size(); ++i) {
|
||||
std::string_view trimmed = Trim(stripped[i]);
|
||||
std::int64_t delta = ParenDelta(stripped[i]);
|
||||
bool candidate = delta > 0 && !trimmed.empty() && !trimmed.starts_with('#')
|
||||
&& !trimmed.ends_with('{') && !ctx.LineHasComment(i + 1) && !ctx.LineHasMultiLineToken(i + 1);
|
||||
if (candidate) {
|
||||
std::string joined(ctx.Line(i + 1));
|
||||
std::size_t j = i + 1;
|
||||
bool ok = true;
|
||||
while (delta > 0 && j < ctx.lines.size() && j - i <= 4) {
|
||||
std::string_view next = Trim(stripped[j]);
|
||||
// A `{`-ending line is fine when it closes the expression
|
||||
// (a control header's `) {`); mid-expression it means a
|
||||
// lambda body starts — leave those wrapped.
|
||||
bool closes = delta + ParenDelta(stripped[j]) <= 0;
|
||||
if (next.empty() || (next.ends_with('{') && !closes)
|
||||
|| ctx.LineHasComment(j + 1) || ctx.LineHasMultiLineToken(j + 1)) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
while (!joined.empty() && (joined.back() == ' ' || joined.back() == '\t')) joined.pop_back();
|
||||
std::string_view fragment = Trim(ctx.Line(j + 1));
|
||||
// No separator right after an opening paren or before a
|
||||
// closing one — joining must not manufacture `( x` / `x )`.
|
||||
if (!joined.ends_with('(') && !fragment.starts_with(')') && !fragment.starts_with(',')) joined += " ";
|
||||
joined += fragment;
|
||||
delta += ParenDelta(stripped[j]);
|
||||
++j;
|
||||
}
|
||||
for (std::size_t l = i + 1; ok && l <= j; ++l) ok = !ctx.Suppressed("wrap-join", l);
|
||||
if (ok && delta <= 0 && joined.size() <= 250) {
|
||||
outLines.push_back(std::move(joined));
|
||||
i = j - 1; // consumed through line j-1 (0-based i)
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
} else if (delta == 0 && i + 1 < ctx.lines.size() && !trimmed.starts_with('#')
|
||||
&& !ctx.LineHasComment(i + 1) && !ctx.LineHasMultiLineToken(i + 1)) {
|
||||
auto isOpStart = [](std::string_view s) {
|
||||
return s.starts_with("&&") || s.starts_with("||") || s.starts_with("| ");
|
||||
};
|
||||
// Operator-style continuation chain (`a\n && b\n && c`).
|
||||
// Joined when the WHOLE chain stays within 250 columns —
|
||||
// longer conditions legitimately wrap. Same mechanics as the
|
||||
// paren join: chain lines must be comment-free, raw-string
|
||||
// free, and paren-balanced.
|
||||
if (isOpStart(Trim(stripped[i + 1])) && !isOpStart(trimmed)) {
|
||||
std::string joined(ctx.Line(i + 1));
|
||||
std::size_t j = i + 1;
|
||||
bool ok = true;
|
||||
while (j < ctx.lines.size() && isOpStart(Trim(stripped[j]))) {
|
||||
if (ParenDelta(stripped[j]) != 0 || ctx.LineHasComment(j + 1) || ctx.LineHasMultiLineToken(j + 1)) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
while (!joined.empty() && (joined.back() == ' ' || joined.back() == '\t')) joined.pop_back();
|
||||
joined += " ";
|
||||
joined += Trim(ctx.Line(j + 1));
|
||||
++j;
|
||||
}
|
||||
for (std::size_t l = i + 1; ok && l <= j; ++l) ok = !ctx.Suppressed("wrap-join", l);
|
||||
if (ok && joined.size() <= 250) {
|
||||
outLines.push_back(std::move(joined));
|
||||
i = j - 1; // consumed the chain
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
outLines.emplace_back(ctx.Line(i + 1));
|
||||
}
|
||||
if (!changed) return;
|
||||
std::string out;
|
||||
for (std::size_t i = 0; i < outLines.size(); ++i) {
|
||||
out += outLines[i];
|
||||
if (i + 1 < outLines.size() || ctx.content.ends_with('\n')) out += '\n';
|
||||
}
|
||||
ctx.SetContent(std::move(out));
|
||||
}
|
||||
});
|
||||
|
||||
// No space padding inside parens: `( x` / `x )` → `(x` / `x)`. Only
|
||||
// intra-line (a line legitimately ends with '(' when a call wraps);
|
||||
// string/comment interiors are excluded via the stripped text.
|
||||
cfg.AddLintRule("paren-spacing", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
const std::string& code = ctx.CommentStripped();
|
||||
std::vector<std::pair<std::size_t, std::size_t>> cuts; // [begin, end) spans of spaces to delete
|
||||
for (std::size_t i = 0; i < code.size(); ++i) {
|
||||
if (code[i] == '(' ) {
|
||||
std::size_t j = i + 1;
|
||||
while (j < code.size() && code[j] == ' ') ++j;
|
||||
if (j > i + 1 && j < code.size() && code[j] != '\n' && code[j] != '\r') cuts.push_back({i + 1, j});
|
||||
} else if (code[i] == ')') {
|
||||
std::size_t j = i;
|
||||
while (j > 0 && code[j - 1] == ' ') --j;
|
||||
// Only single-space padding: multi-space runs are usually
|
||||
// deliberate alignment columns.
|
||||
if (j == i - 1 && j > 0 && code[j - 1] != '\n' && code[j - 1] != ',') cuts.push_back({j, i});
|
||||
}
|
||||
}
|
||||
if (cuts.empty()) return;
|
||||
std::string out = ctx.content;
|
||||
for (auto it = cuts.rbegin(); it != cuts.rend(); ++it) out.erase(it->first, it->second - it->first);
|
||||
ctx.SetContent(std::move(out));
|
||||
});
|
||||
|
||||
cfg.AddLintRule("trim-trailing-ws", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
std::string out;
|
||||
out.reserve(ctx.content.size());
|
||||
for (std::size_t n = 1; n <= ctx.lines.size(); ++n) {
|
||||
std::string_view line = ctx.Line(n);
|
||||
// Byte fidelity on CRLF files: peel the \r, trim, put it back.
|
||||
bool crlf = line.ends_with('\r');
|
||||
if (crlf) line.remove_suffix(1);
|
||||
while (line.ends_with(' ') || line.ends_with('\t')) line.remove_suffix(1);
|
||||
out += line;
|
||||
if (crlf) out += '\r';
|
||||
// The last line only had a newline if the file ended with one —
|
||||
// preserve that byte exactly so this rule doesn't shadow
|
||||
// final-newline.
|
||||
if (n < ctx.lines.size() || ctx.content.ends_with('\n')) out += '\n';
|
||||
}
|
||||
ctx.SetContent(std::move(out));
|
||||
});
|
||||
|
||||
cfg.AddLintRule("final-newline", [](LintContext& ctx) {
|
||||
if (!IsCppFile(ctx)) return;
|
||||
if (!ctx.content.empty() && !ctx.content.ends_with('\n')) {
|
||||
ctx.SetContent(ctx.content + '\n');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
40
project.cpp
Normal file
40
project.cpp
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
import std;
|
||||
import Crafter.Build;
|
||||
namespace fs = std::filesystem;
|
||||
using namespace Crafter;
|
||||
|
||||
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
|
||||
std::vector<std::string> depArgs(args.begin(), args.end());
|
||||
const bool useLocal = std::erase(depArgs, "--local") > 0;
|
||||
|
||||
Configuration cfg;
|
||||
cfg.path = "./";
|
||||
cfg.name = "Crafter.LintRules";
|
||||
cfg.outputName = "Crafter.LintRules";
|
||||
cfg.type = ConfigurationType::LibraryStatic;
|
||||
ApplyStandardArgs(cfg, args);
|
||||
// No dependency on Crafter.Build, on purpose. The rules only ever run
|
||||
// inside a crafter-build process, which provides the symbols, and a host
|
||||
// build already sees the Crafter.Build modules through the PCM cache
|
||||
// crafter-build keeps for its own project files — declaring the library
|
||||
// here would make every consumer clone and build all of crafter-build
|
||||
// just to lint.
|
||||
std::array<fs::path, 1> ifaces = { "interfaces/Crafter.LintRules" };
|
||||
std::array<fs::path, 0> impls = {};
|
||||
cfg.GetInterfacesAndImplementations(ifaces, impls);
|
||||
|
||||
// The rule test compiles the module as its own interface and links
|
||||
// crafter-build to run the linter in-process: from git by default, or
|
||||
// the sibling checkout with `crafter-build test --local`. Host only,
|
||||
// like the rules themselves.
|
||||
if (cfg.target == "x86_64-pc-linux-gnu") {
|
||||
Configuration* build = useLocal
|
||||
? LocalProject({ .projectFile = "../Crafter.Build/project.cpp", .args = depArgs })
|
||||
: GitProject({ .source = { .url = "https://forgejo.catcrafts.net/Catcrafts/Crafter.Build.git" }, .args = depArgs });
|
||||
cfg.AddTest("HouseRules", ifaces).Dependencies({ build });
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
513
tests/HouseRules/main.cpp
Normal file
513
tests/HouseRules/main.cpp
Normal file
|
|
@ -0,0 +1,513 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
import std;
|
||||
import Crafter.Build;
|
||||
import Crafter.LintRules;
|
||||
namespace fs = std::filesystem;
|
||||
using namespace Crafter;
|
||||
|
||||
// Validates the house-style ruleset — the transforms and reports every repo
|
||||
// that imports Crafter.LintRules relies on. Each case writes a scratch file,
|
||||
// runs ONE rule via the glob filter, and asserts the findings and/or
|
||||
// rewritten bytes.
|
||||
namespace {
|
||||
std::int32_t Failures = 0;
|
||||
|
||||
void Check(bool cond, std::string_view msg) {
|
||||
if (!cond) {
|
||||
std::println(std::cerr, "FAIL: {}", msg);
|
||||
++Failures;
|
||||
}
|
||||
}
|
||||
|
||||
struct RuleRun {
|
||||
LintSummary summary;
|
||||
std::string text; // file content after the run
|
||||
};
|
||||
|
||||
RuleRun RunRule(std::string_view content, std::string_view rule, LintMode mode) {
|
||||
static std::int32_t Counter = 0;
|
||||
fs::path dir = fs::temp_directory_path() / "crafter-build-house-rules" / std::format("case-{}", Counter++);
|
||||
fs::remove_all(dir);
|
||||
fs::create_directories(dir);
|
||||
{
|
||||
std::ofstream f(dir / "f.cpp", std::ios::binary | std::ios::trunc);
|
||||
f.write(content.data(), static_cast<std::streamsize>(content.size()));
|
||||
}
|
||||
Configuration cfg;
|
||||
cfg.path = dir;
|
||||
cfg.name = "house-fixture";
|
||||
cfg.outputName = "house-fixture";
|
||||
cfg.target = HostTarget();
|
||||
std::array<fs::path, 0> ifaces = {};
|
||||
std::array<fs::path, 1> impls = { "f" };
|
||||
cfg.GetInterfacesAndImplementations(ifaces, impls);
|
||||
LintRules::AddRules(cfg);
|
||||
RunLintOptions opts;
|
||||
opts.mode = mode;
|
||||
opts.globs = { std::string(rule) };
|
||||
RuleRun run;
|
||||
run.summary = RunLint(cfg, opts);
|
||||
std::ifstream f(dir / "f.cpp", std::ios::binary);
|
||||
std::stringstream buffer;
|
||||
buffer << f.rdbuf();
|
||||
run.text = std::move(buffer).str();
|
||||
return run;
|
||||
}
|
||||
|
||||
bool HasFinding(const LintSummary& s, std::string_view fragment) {
|
||||
return std::any_of(s.findings.begin(), s.findings.end(), [&](const LintFinding& f) { return f.message.contains(fragment); });
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
// fixed-width-types: int/long long convert; main/argc and extern "C" stay.
|
||||
{
|
||||
RuleRun r = RunRule("int Foo(long long v) { int x = 5; return x; }\n" "extern \"C\" int setenv(const char* n, const char* v, int o);\n" "int main(int argc, char** argv) { return 0; }\n", "fixed-width-types", LintMode::Apply);
|
||||
Check(r.text.contains("std::int32_t Foo(std::int64_t v) { std::int32_t x = 5;"), "fixed-width converts int and long long");
|
||||
Check(r.text.contains("extern \"C\" int setenv"), "extern \"C\" prototype keeps int");
|
||||
Check(r.text.contains("int main(int argc"), "main/argc keep int");
|
||||
}
|
||||
|
||||
// fixed-width-types is signed/unsigned aware, in any specifier order;
|
||||
// bare char (text) and long double (floating) are not integers.
|
||||
{
|
||||
RuleRun r = RunRule("void F() {\n"
|
||||
" unsigned a = 1;\n"
|
||||
" unsigned int b = 2;\n"
|
||||
" unsigned long long c = 3;\n"
|
||||
" long unsigned int d = 4;\n"
|
||||
" unsigned short e = 5;\n"
|
||||
" signed f = 6;\n"
|
||||
" signed char g = 7;\n"
|
||||
" auto h = static_cast<unsigned char>(g);\n"
|
||||
" char text = 'x';\n"
|
||||
" long double pi = 3.14L;\n"
|
||||
"}\n",
|
||||
"fixed-width-types", LintMode::Apply);
|
||||
Check(r.text.contains("std::uint32_t a = 1;"), "bare unsigned -> uint32");
|
||||
Check(r.text.contains("std::uint32_t b = 2;"), "unsigned int -> uint32");
|
||||
Check(r.text.contains("std::uint64_t c = 3;"), "unsigned long long -> uint64");
|
||||
Check(r.text.contains("std::uint64_t d = 4;"), "long unsigned int (reordered) -> uint64");
|
||||
Check(r.text.contains("std::uint16_t e = 5;"), "unsigned short -> uint16");
|
||||
Check(r.text.contains("std::int32_t f = 6;"), "bare signed -> int32");
|
||||
Check(r.text.contains("std::int8_t g = 7;"), "signed char -> int8");
|
||||
Check(r.text.contains("static_cast<std::uint8_t>(g)"), "unsigned char -> uint8");
|
||||
Check(r.text.contains("char text = 'x';"), "bare char stays (text, not an integer)");
|
||||
Check(r.text.contains("long double pi = 3.14L;"), "long double stays (floating type)");
|
||||
}
|
||||
|
||||
// brace-style: Allman brace joins; standalone scope block stays.
|
||||
{
|
||||
RuleRun r = RunRule("void Foo()\n{\n}\n\nvoid Bar() {\n Baz();\n {\n Qux();\n }\n}\n", "brace-style", LintMode::Apply);
|
||||
Check(r.text.contains("void Foo() {"), "Allman brace joined onto header");
|
||||
Check(r.text.contains("Baz();\n {"), "scope block brace untouched");
|
||||
}
|
||||
|
||||
// if-single-line: short body joins; braced body stays.
|
||||
{
|
||||
RuleRun r = RunRule("void F(bool b) {\n if (b)\n Run();\n if (b) {\n Run();\n }\n}\n", "if-single-line", LintMode::Apply);
|
||||
Check(r.text.contains("if (b) Run();"), "single-statement if body joined");
|
||||
Check(r.text.contains("if (b) {"), "braced if body untouched");
|
||||
}
|
||||
|
||||
// single-declaration splits on the AST, so each declarator carries its own
|
||||
// resolved type. That is the whole reason it is not a token rule: copying
|
||||
// the head's type prefix turns `int* a, b;` into `int* a; int* b;` and
|
||||
// silently changes b from int to int*.
|
||||
{
|
||||
RuleRun r = RunRule("#include <vector>\n"
|
||||
"void F() {\n"
|
||||
" bool a = false, b = true;\n"
|
||||
" int* ptrA = nullptr, *ptrB = nullptr;\n"
|
||||
" int* mixed = nullptr, plain = 7;\n"
|
||||
" std::vector<int> tmplA{}, tmplB{};\n"
|
||||
" int callA = g(), callB = h();\n"
|
||||
" int keep = 1, kept = 2; // trailing comment\n"
|
||||
"}\n",
|
||||
"single-declaration", LintMode::Apply);
|
||||
Check(r.text.contains("bool a = false;\n bool b = true;"), "single-declaration: simple split");
|
||||
Check(r.text.contains("int* ptrA = nullptr;\n int* ptrB = nullptr;"), "single-declaration: pointers split, star kept on the type");
|
||||
// The case a token-based splitter gets wrong.
|
||||
Check(r.text.contains("int* mixed = nullptr;\n int plain = 7;"), "single-declaration: only the starred declarator is a pointer");
|
||||
Check(r.text.contains("std::vector<int> tmplA{};\n std::vector<int> tmplB{};"), "single-declaration: template arguments are not a bail-out");
|
||||
Check(r.text.contains("int callA = g();\n int callB = h();"), "single-declaration: call initialisers are not a bail-out");
|
||||
// A comment after the ';' is outside the replaced range, so it survives;
|
||||
// the line-based version refused the whole line instead.
|
||||
Check(r.text.contains("int keep = 1;\n int kept = 2; // trailing comment"), "single-declaration: trailing comment survives the split");
|
||||
RuleRun again = RunRule(r.text, "single-declaration", LintMode::Apply);
|
||||
Check(again.summary.changedFiles.empty(), "single-declaration: idempotent");
|
||||
}
|
||||
|
||||
// wrap-join: short wrapped call joins; operator chain joins; long stays.
|
||||
{
|
||||
RuleRun r = RunRule("void F() {\n G(alpha,\n beta);\n bool x = alpha\n && beta;\n}\n", "wrap-join", LintMode::Apply);
|
||||
Check(r.text.contains("G(alpha, beta);"), "wrapped call arguments joined");
|
||||
Check(r.text.contains("bool x = alpha && beta;"), "operator continuation joined");
|
||||
}
|
||||
|
||||
// format-concat: literal-adjacent + rewrites; += RHS rewrites; args survive.
|
||||
{
|
||||
RuleRun r = RunRule("void F(std::string name, std::string cmd) {\n"
|
||||
" std::string a = name + \".cpp\";\n"
|
||||
" std::string b = \"pre-\" + name + \"-post\";\n"
|
||||
" cmd += \" \" + name;\n"
|
||||
" std::string keep = name + cmd;\n"
|
||||
" fs::path p;\n"
|
||||
" std::string c = p.stem().string() + \".pcm\";\n"
|
||||
" fs::path d = std::string(cmd) + \".so\";\n"
|
||||
"}\n",
|
||||
"format-concat", LintMode::Apply);
|
||||
Check(r.text.contains("std::string a = std::format(\"{}.cpp\", name);"), "trailing literal converts");
|
||||
Check(!r.text.contains("namestd::format"), "replacement splices at the operand boundary");
|
||||
Check(r.text.contains("std::string b = std::format(\"pre-{}-post\", name);"), "sandwich chain converts");
|
||||
Check(r.text.contains("cmd += std::format(\" {}\", name);"), "+= RHS converts");
|
||||
Check(r.text.contains("std::string keep = name + cmd;"), "literal-free + is left alone");
|
||||
Check(r.text.contains("std::string c = std::format(\"{}.pcm\", p.stem().string());"), "call-chain left operand consumed whole (the stringstd regression)");
|
||||
Check(r.text.contains("fs::path d = std::format(\"{}.so\", std::string(cmd));"), "constructor-call left operand consumed whole");
|
||||
}
|
||||
{
|
||||
// Ternary and raw-string lines are reported, never rewritten.
|
||||
RuleRun r = RunRule("std::string F(bool b, std::string n) { return b ? n + \".x\" : n; }\n", "format-concat", LintMode::Report);
|
||||
Check(HasFinding(r.summary, "not auto-fixable"), "ternary concat reports instead of fixing");
|
||||
Check(r.text.contains("n + \".x\""), "ternary concat untouched on disk");
|
||||
}
|
||||
|
||||
// paren-spacing: single-space padding removed; wrapped call ends keep.
|
||||
{
|
||||
RuleRun r = RunRule("void F() {\n G( x );\n}\n", "paren-spacing", LintMode::Apply);
|
||||
Check(r.text.contains("G(x);"), "paren padding removed");
|
||||
}
|
||||
|
||||
// naming: wrong-case function/type/static/global flagged; camel local passes.
|
||||
{
|
||||
RuleRun r = RunRule("namespace {\n"
|
||||
" std::int32_t bad_global = 0;\n"
|
||||
" struct lint_thing {};\n"
|
||||
"}\n"
|
||||
"void lower_func() {\n"
|
||||
" static bool lowerStatic = false;\n"
|
||||
" std::int32_t fineLocal = 1;\n"
|
||||
"}\n",
|
||||
"naming", LintMode::Report);
|
||||
Check(HasFinding(r.summary, "'bad_global' should be PascalCase"), "lowercase global flagged");
|
||||
Check(HasFinding(r.summary, "'lint_thing' should be PascalCase"), "lowercase type flagged");
|
||||
Check(HasFinding(r.summary, "'lower_func' should be PascalCase"), "lowercase function flagged");
|
||||
Check(HasFinding(r.summary, "'lowerStatic' should be PascalCase"), "camel static flagged");
|
||||
Check(!HasFinding(r.summary, "fineLocal"), "camelCase local passes");
|
||||
}
|
||||
{
|
||||
// Statement calls with inline lambda arguments are NOT function
|
||||
// definitions (the any_of regression); a genuine lowercase one-liner
|
||||
// method still is.
|
||||
RuleRun r = RunRule("struct Holder {\n"
|
||||
" bool clean() const { return true; }\n"
|
||||
"};\n"
|
||||
"void T(std::vector<std::int32_t>& v) {\n"
|
||||
" bool x = std::any_of(v.begin(), v.end(), [](std::int32_t n) { return n > 0; });\n"
|
||||
" std::erase_if(v, [](std::int32_t n) { return n < 0; });\n"
|
||||
"}\n",
|
||||
"naming", LintMode::Report);
|
||||
Check(!HasFinding(r.summary, "any_of"), "call with lambda argument is not a function definition");
|
||||
Check(!HasFinding(r.summary, "erase_if"), "bare statement call is not a function definition");
|
||||
Check(HasFinding(r.summary, "'clean' should be PascalCase"), "lowercase one-liner method still flagged");
|
||||
}
|
||||
|
||||
// enum-class + no-iostream-print reports.
|
||||
{
|
||||
RuleRun r = RunRule("enum Color { Red };\n", "enum-class", LintMode::Report);
|
||||
Check(HasFinding(r.summary, "enum class"), "plain enum flagged");
|
||||
}
|
||||
{
|
||||
RuleRun r = RunRule("void F() { std::cout << 1; }\n", "no-iostream-print", LintMode::Report);
|
||||
Check(HasFinding(r.summary, "std::println"), "std::cout flagged");
|
||||
}
|
||||
|
||||
// The whole ruleset is idempotent: a second Apply changes nothing.
|
||||
{
|
||||
std::string_view source = "int Foo()\n{\n std::string s = std::string(\"a\") + \"b\";\n if (true)\n return 1;\n return 0;\n}\n";
|
||||
static constexpr std::string_view AllRules = "*";
|
||||
RuleRun first = RunRule(source, AllRules, LintMode::Apply);
|
||||
RuleRun second = RunRule(first.text, AllRules, LintMode::Apply);
|
||||
Check(second.summary.changedFiles.empty(), "second apply of the full ruleset is a no-op");
|
||||
Check(first.text != source, "first apply actually changed the fixture");
|
||||
}
|
||||
|
||||
// Suppression directives against house transforms: the driver reverts
|
||||
// line-preserving edits (fixed-width) and the count-changing rules check
|
||||
// Suppressed() themselves (wrap-join).
|
||||
{
|
||||
RuleRun r = RunRule("void F() {\n"
|
||||
" // lint-disable-next-line fixed-width-types\n"
|
||||
" int keep = 1;\n"
|
||||
" int convert = 2;\n"
|
||||
"}\n",
|
||||
"fixed-width-types", LintMode::Apply);
|
||||
Check(r.text.contains("int keep = 1;"), "next-line directive keeps the suppressed int");
|
||||
Check(r.text.contains("std::int32_t convert = 2;"), "unsuppressed line still converts");
|
||||
}
|
||||
{
|
||||
RuleRun r = RunRule("void F() {\n"
|
||||
" // lint-disable-next-line wrap-join\n"
|
||||
" G(alpha,\n"
|
||||
" beta);\n"
|
||||
" H(alpha,\n"
|
||||
" beta);\n"
|
||||
"}\n",
|
||||
"wrap-join", LintMode::Apply);
|
||||
Check(r.text.contains("G(alpha,\n"), "suppressed wrap stays wrapped");
|
||||
Check(r.text.contains("H(alpha, beta);"), "unsuppressed wrap still joins");
|
||||
}
|
||||
|
||||
// wrap-join converges in ONE run: joining the inner paren wrap balances
|
||||
// the && line, which only then becomes an operator-joinable continuation.
|
||||
{
|
||||
RuleRun r = RunRule("void F() {\n"
|
||||
" bool ok = alpha\n"
|
||||
" && beta(gamma,\n"
|
||||
" delta);\n"
|
||||
"}\n",
|
||||
"wrap-join", LintMode::Apply);
|
||||
Check(r.text.contains("bool ok = alpha && beta(gamma, delta);"), "self-enabling joins reach the fixpoint in one apply");
|
||||
RuleRun second = RunRule(r.text, "wrap-join", LintMode::Apply);
|
||||
Check(second.summary.changedFiles.empty(), "wrap-join is idempotent after the fixpoint");
|
||||
}
|
||||
|
||||
// The guards used to be substring probes over the raw line, so a literal
|
||||
// whose TEXT contained `//` or `R"` looked like a comment or a raw string
|
||||
// and silently disabled the rule. Both shapes occur in this repo's own
|
||||
// sources — "MARKER" ends in the characters R", and any string mentioning
|
||||
// a lint-disable directive contains //.
|
||||
{
|
||||
RuleRun r = RunRule("void F() {\n" " auto hit = text.find(\"MARKER\",\n" " start);\n" "}\n", "wrap-join", LintMode::Apply);
|
||||
Check(r.text.contains("text.find(\"MARKER\", start);"), "R\" inside a literal no longer blocks wrap-join");
|
||||
}
|
||||
{
|
||||
RuleRun r = RunRule("void F() {\n" " Check(read() == \"// lint-disable-next-line trim\\n\",\n" " \"message\");\n" "}\n", "wrap-join", LintMode::Apply);
|
||||
Check(r.text.contains("\\n\", \"message\");"), "// inside a literal no longer blocks wrap-join");
|
||||
}
|
||||
|
||||
// A real trailing comment still blocks the join: text pulled up past a
|
||||
// `//` would be swallowed by it.
|
||||
{
|
||||
RuleRun r = RunRule("void F() {\n" " auto v = g(alpha, // why\n" " beta);\n" "}\n", "wrap-join", LintMode::Apply);
|
||||
Check(r.text.contains("g(alpha, // why\n"), "a real comment still blocks wrap-join");
|
||||
}
|
||||
|
||||
// A genuinely multi-line literal is never reflowed — joining its lines
|
||||
// would change the string's contents.
|
||||
{
|
||||
std::string_view source = "void F() {\n"
|
||||
" auto text = R\"sql(SELECT a,\n"
|
||||
" b FROM t)sql\";\n"
|
||||
"}\n";
|
||||
RuleRun r = RunRule(source, "wrap-join", LintMode::Apply);
|
||||
Check(r.text == source, "wrap-join leaves a multi-line raw string alone");
|
||||
RuleRun paren = RunRule(source, "paren-spacing", LintMode::Apply);
|
||||
Check(paren.text == source, "paren-spacing leaves a multi-line raw string alone");
|
||||
}
|
||||
|
||||
// Type keywords inside a literal are text, not declarations.
|
||||
{
|
||||
std::string_view source = "void F() {\n"
|
||||
" auto sql = R\"q(int x; unsigned long y;)q\";\n"
|
||||
"}\n";
|
||||
RuleRun r = RunRule(source, "fixed-width-types", LintMode::Apply);
|
||||
Check(r.text == source, "fixed-width-types leaves type names inside a raw string alone");
|
||||
}
|
||||
|
||||
// no-char-pointer reads the AST, so it distinguishes OUR char* from one
|
||||
// whose spelling belongs to somebody else's header. This is what replaced
|
||||
// the substring denylist (argv, getenv, c_str, reinterpret_cast, …): each
|
||||
// entry there disabled the rule for a whole line, and the list could only
|
||||
// grow as new libraries arrived.
|
||||
{
|
||||
RuleRun r = RunRule("#include <cstdlib>\n"
|
||||
"#include <string>\n"
|
||||
"extern \"C\" const char* CApiEntry(const char* path);\n"
|
||||
"char* OurBadApi(char* input) { return input; }\n"
|
||||
"void F() {\n"
|
||||
" char* fromLibc = std::getenv(\"HOME\");\n"
|
||||
" std::string mine = \"ok\";\n"
|
||||
" const char* toLibc = mine.c_str();\n"
|
||||
" auto raw = reinterpret_cast<char*>(&mine);\n"
|
||||
"}\n",
|
||||
"no-char-pointer", LintMode::Report);
|
||||
// Ours, so reported: the declaration and its parameter.
|
||||
Check(HasFinding(r.summary, "'OurBadApi'"), "no-char-pointer: our own char* return is reported");
|
||||
Check(HasFinding(r.summary, "'input'"), "no-char-pointer: our own char* parameter is reported");
|
||||
// Foreign, so exempt — each for a reason, not by name.
|
||||
Check(!HasFinding(r.summary, "'CApiEntry'"), "no-char-pointer: extern \"C\" declaration is exempt");
|
||||
Check(!HasFinding(r.summary, "'path'"), "no-char-pointer: extern \"C\" parameter is exempt");
|
||||
Check(!HasFinding(r.summary, "'fromLibc'"), "no-char-pointer: a value from libc is exempt");
|
||||
Check(!HasFinding(r.summary, "'toLibc'"), "no-char-pointer: a value from c_str() is exempt");
|
||||
// A local whose deduced type is char* is still our declaration, so it
|
||||
// is reported. The old denylist exempted every line mentioning
|
||||
// reinterpret_cast; a deliberate low-level cast now takes an explicit
|
||||
// lint-disable comment, which is at least visible at the site.
|
||||
Check(HasFinding(r.summary, "'raw'"), "no-char-pointer: a deduced char* local is still ours");
|
||||
}
|
||||
|
||||
// Cases the line-based heuristic structurally could not see. It only looked
|
||||
// at declarations starting at cumulative paren depth 0 and inferred scope
|
||||
// from a running {/} count, so a wrapped signature, a specifier split over
|
||||
// two lines, or a local shadowing a member all escaped it.
|
||||
{
|
||||
RuleRun r = RunRule("#include <string>\n"
|
||||
"namespace Outer {\n"
|
||||
" int wrapped_function(\n"
|
||||
" int first,\n"
|
||||
" int second) { return first + second; }\n"
|
||||
" static\n"
|
||||
" int splitStatic = 1;\n"
|
||||
" struct Holder {\n"
|
||||
" int Member = 0;\n"
|
||||
" void Method() {\n"
|
||||
" int Local = 1;\n"
|
||||
" (void)Local;\n"
|
||||
" }\n"
|
||||
" };\n"
|
||||
"}\n"
|
||||
"extern \"C\" int c_api_entry(const char* name);\n",
|
||||
"naming", LintMode::Report);
|
||||
// A signature wrapped over lines is still a function declaration.
|
||||
Check(HasFinding(r.summary, "'wrapped_function' should be PascalCase"), "naming: wrapped signature is seen");
|
||||
// `static` on its own line still applies to the declaration below it.
|
||||
Check(HasFinding(r.summary, "'splitStatic' should be PascalCase"), "naming: split specifier is seen");
|
||||
// Members are camelCase; the enclosing kind decides, not a brace count.
|
||||
Check(HasFinding(r.summary, "'Member' should be camelCase"), "naming: member is checked as a member");
|
||||
// A local inside a method is a local, not a member and not a global.
|
||||
Check(HasFinding(r.summary, "'Local' should be camelCase"), "naming: local inside a method is a local");
|
||||
// Named by libc, not by us.
|
||||
Check(!HasFinding(r.summary, "c_api_entry"), "naming: extern \"C\" declaration is exempt");
|
||||
Check(!HasFinding(r.summary, "'Method'"), "naming: PascalCase method passes");
|
||||
Check(!HasFinding(r.summary, "'Holder'"), "naming: PascalCase type passes");
|
||||
}
|
||||
|
||||
// fixed-width-types must not rewrite an integer whose width somebody else's
|
||||
// header chose — the rewrite would leave code that no longer matches the API
|
||||
// it calls. Derived from the AST, so the exemption is per-declaration rather
|
||||
// than the old per-line textual one, which both missed cases and disabled
|
||||
// the rule for anything else sharing a line with `argc`/`extern "`.
|
||||
{
|
||||
RuleRun r = RunRule("#include <cstdlib>\n"
|
||||
"extern \"C\" unsigned long CApiCall(unsigned int flags);\n"
|
||||
"long OurOwnApi(int value) { return value; }\n"
|
||||
"void F() {\n"
|
||||
" unsigned long fromLibc = std::strtoul(\"1\", nullptr, 10);\n"
|
||||
" unsigned ours = 1;\n"
|
||||
" (void)fromLibc; (void)ours;\n"
|
||||
"}\n"
|
||||
"int main(int argc, char** argv) {\n"
|
||||
" for (int i = 0; i < argc; ++i) { (void)argv[i]; }\n"
|
||||
" return 0;\n"
|
||||
"}\n",
|
||||
"fixed-width-types", LintMode::Apply);
|
||||
// Somebody else's widths, kept.
|
||||
Check(r.text.contains("extern \"C\" unsigned long CApiCall(unsigned int flags);"), "fixed-width: extern \"C\" signature keeps its widths");
|
||||
Check(r.text.contains("unsigned long fromLibc = std::strtoul"), "fixed-width: a value from a C library keeps its width");
|
||||
Check(r.text.contains("int main(int argc, char** argv)"), "fixed-width: main's signature is untouched");
|
||||
// Ours, converted.
|
||||
Check(r.text.contains("std::int64_t OurOwnApi(std::int32_t value)"), "fixed-width: our own signature converts");
|
||||
Check(r.text.contains("std::uint32_t ours = 1;"), "fixed-width: our own local converts");
|
||||
// The loop counter inside main's BODY is ordinary code. The old rule
|
||||
// skipped it because `argc` appeared on the same line; only the
|
||||
// signature is exempt now, not everything near it.
|
||||
Check(r.text.contains("for (std::int32_t i = 0;"), "fixed-width: main's body is not exempt, only its signature");
|
||||
}
|
||||
|
||||
// enum-class asks for the next TOKEN after `enum`, so a declaration split
|
||||
// over lines reads the same as one that is not. The regex it replaced
|
||||
// required the name to follow `enum` on the same line.
|
||||
{
|
||||
RuleRun r = RunRule("enum Plain { A };\n"
|
||||
"enum\n"
|
||||
" Split { B };\n"
|
||||
"enum class Scoped { C };\n"
|
||||
"enum\n"
|
||||
" class SplitScoped { D };\n"
|
||||
"enum struct AlsoFine { E };\n",
|
||||
"enum-class", LintMode::Report);
|
||||
Check(r.summary.findings.size() == 2, std::format("enum-class: exactly the two plain enums ({} found)", r.summary.findings.size()));
|
||||
const bool onFirst = std::any_of(r.summary.findings.begin(), r.summary.findings.end(), [](const LintFinding& f) { return f.line == 1; });
|
||||
const bool onSplit = std::any_of(r.summary.findings.begin(), r.summary.findings.end(), [](const LintFinding& f) { return f.line == 2; });
|
||||
Check(onFirst, "enum-class: single-line plain enum reported");
|
||||
Check(onSplit, "enum-class: line-split plain enum reported at the keyword");
|
||||
}
|
||||
|
||||
// const-local's mutation analysis is exact for scalars: assignment, ++/--,
|
||||
// address-of and binding to a non-const reference are the only ways to
|
||||
// write one, and all four are tracked. Both directions matter — a missed
|
||||
// write means advising const on something that cannot be const.
|
||||
{
|
||||
RuleRun r = RunRule("void Mutate(int& out);\n"
|
||||
"void ReadOnly(const int& in);\n"
|
||||
"void ByValue(int v);\n"
|
||||
"int Compute();\n"
|
||||
"void F() {\n"
|
||||
" int neverWritten = 1;\n"
|
||||
" int assigned = 1; assigned = 2;\n"
|
||||
" int incremented = 1; ++incremented;\n"
|
||||
" int compound = 1; compound += 2;\n"
|
||||
" int addressed = 1; int* taken = &addressed;\n"
|
||||
" int toMutatingRef = 1; Mutate(toMutatingRef);\n"
|
||||
" int toConstRef = 1; ReadOnly(toConstRef);\n"
|
||||
" int toByValue = 1; ByValue(toByValue);\n"
|
||||
" int boundToRef = 1; int& alias = boundToRef;\n"
|
||||
" for (int loop = 0; loop < 1; ++loop) { (void)loop; }\n"
|
||||
" (void)taken; (void)alias;\n"
|
||||
"}\n",
|
||||
"const-local", LintMode::Report);
|
||||
Check(HasFinding(r.summary, "'neverWritten'"), "const-local: an unwritten local is reported");
|
||||
Check(HasFinding(r.summary, "'toConstRef'"), "const-local: passing to a const& is not a write");
|
||||
Check(HasFinding(r.summary, "'toByValue'"), "const-local: passing by value is not a write");
|
||||
Check(!HasFinding(r.summary, "'assigned'"), "const-local: assignment is a write");
|
||||
Check(!HasFinding(r.summary, "'incremented'"), "const-local: ++ is a write");
|
||||
Check(!HasFinding(r.summary, "'compound'"), "const-local: += is a write");
|
||||
Check(!HasFinding(r.summary, "'addressed'"), "const-local: taking an address counts as a write");
|
||||
Check(!HasFinding(r.summary, "'toMutatingRef'"), "const-local: binding to a non-const& parameter is a write");
|
||||
Check(!HasFinding(r.summary, "'boundToRef'"), "const-local: binding to a non-const& local is a write");
|
||||
Check(!HasFinding(r.summary, "'loop'"), "const-local: a mutated loop counter is not reported");
|
||||
// Pointers and range-for bindings are excluded: `T* const p` and
|
||||
// `for (T* const x : …)` are not spellings anybody writes.
|
||||
Check(!HasFinding(r.summary, "'taken'"), "const-local: pointer locals are out of scope");
|
||||
}
|
||||
{
|
||||
RuleRun r = RunRule("void F() {\n" " for (int each : Range()) { (void)each; }\n" "}\n", "const-local", LintMode::Report);
|
||||
Check(!HasFinding(r.summary, "'each'"), "const-local: a range-for binding is not reported");
|
||||
}
|
||||
|
||||
// constexpr-constant asks clang's constant evaluator, not the tokens of the
|
||||
// initialiser. sizeof and a fold over other constants are constant
|
||||
// expressions that no token scan can recognise; a call result is not.
|
||||
{
|
||||
RuleRun r = RunRule("int Compute();\n"
|
||||
"constexpr int Base = 4;\n"
|
||||
"struct Big { int a, b; };\n"
|
||||
"void F() {\n"
|
||||
" const int literal = 4;\n"
|
||||
" const int folded = 1 << 4;\n"
|
||||
" const int fromSizeof = sizeof(Big);\n"
|
||||
" const int fromOtherConstant = Base + 1;\n"
|
||||
" const int fromCall = Compute();\n"
|
||||
" constexpr int already = 8;\n"
|
||||
" (void)literal; (void)folded; (void)fromSizeof;\n"
|
||||
" (void)fromOtherConstant; (void)fromCall; (void)already;\n"
|
||||
"}\n",
|
||||
"constexpr-constant", LintMode::Report);
|
||||
Check(HasFinding(r.summary, "'literal'"), "constexpr: a literal constant is reported");
|
||||
Check(HasFinding(r.summary, "'folded'"), "constexpr: an operator fold over literals is reported");
|
||||
// Neither of these is reachable from a token scan of the initialiser.
|
||||
Check(HasFinding(r.summary, "'fromSizeof'"), "constexpr: sizeof folds");
|
||||
Check(HasFinding(r.summary, "'fromOtherConstant'"), "constexpr: a fold over another constant folds");
|
||||
Check(!HasFinding(r.summary, "'fromCall'"), "constexpr: a call result is not a constant expression");
|
||||
Check(!HasFinding(r.summary, "'already'"), "constexpr: an existing constexpr is not re-reported");
|
||||
}
|
||||
|
||||
if (Failures > 0) {
|
||||
std::println(std::cerr, "{} assertions failed", Failures);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Loading…
Reference in a new issue