Author: small Fu Ge blog: bugstack. Cn, mp.weixin.qq.com/s/RwzprbY2A…

One, foreword

Are you curious about the technology you use?

Although we are all called code farmers, and we all write code, we all do different things because of the needs of the scene.

Some standardize, some develop components, some write the business, and some do validation, but the simpler a crUD-like coder is, the more good it uses other people to provide. One moment installing a plug-in, one moment introducing a Jar package, one moment adjusting someone else’s interface, while my own work is like assembling people, and writing the product requirements.

Oh, no. This could be a few years, but there won’t be any technological breakthroughs. Because you’re not curious about the technologies in use and how they’re implemented. Like Ali’s P3C plugin, how did the code check out my crotch pull?

What is P3C plug-in

P3C is the plug-in project name of Ali open source code base. It is an IDEA/Eclipse plug-in used to monitor code quality according to Alibaba Java development manual.

  • Source: github.com/alibaba/p3c

After the plug-in is installed, the code can be statically analyzed according to the programming specification: naming style, constant definition, collection handling, concurrent handling, OOP, control statements, comments, exceptions, and other potential risks in the code, while giving some optimization operations and examples.

  • While adhering to development manual standards and checking with plug-ins, it’s still a good idea to unify coding standards and styles and eliminate some potential risks.
  • If you are a novice programmer or want to write standard code, it is highly recommended that you follow this plugin to assist in your own code development. Of course, if your company also has the corresponding standard manual and plug-in, you can also comply with it after the agreement.

P3C plug-in source code

At the beginning, when I used this kind of code to check the plugins, I was very curious about how it found my shit mountain code and what kind of technical principle it used. If I could analyze whether I could also apply such technical means to other places.

In the analysis of such a code check plug-in, first think to check the source code from IDEA plug-in, see what logic it is, and then analyze how to use it. In fact, this and some other framework source learning are similar, get the official website are documents, GitHub corresponding source code, according to the steps to build, deployment, testing, debugging, analysis, and then find the core principle.

P3C takes IDEA plug-in development as an example, which mainly involves the plug-in part and the protocol part. Because the ability of protocol inspection is combined with the plug-in technology, some IDEA development technologies will be involved. The P3C plug-in also involves technical languages not just Java but also kotlin which is a statically typed programming language that runs on the Java virtual machine.

  • Plugin source: github.com/alibaba/p3c…
  • Protocol source code: github.com/alibaba/p3c…

1. Configure the p3C.xml plug-in

<action class="com.alibaba.p3c.idea.action.AliInspectionAction" id="AliP3CInspectionAction"
        popup="true" text="Code protocol scan" icon="P3cIcons.ANALYSIS_ACTION">
    <keyboard-shortcut keymap="$default"
                       first-keystroke="shift ctrl alt J"/>
    <add-to-group group-id="MainToolBar" anchor="last"/>
    <add-to-group group-id="ProjectViewPopupMenu" anchor="last"/>
    <add-to-group group-id="ChangesViewPopupMenu" anchor="last"/>
    <add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action>
Copy the code
  • The most important thing to look through the source code is to find the entry, which is usually when you use plug-ins, programs, interfaces, etc., the most direct access to that part.
  • So when we use the P3C plugin, the most obvious isCode protocol scanFind the keyword in the source code to see which class configuration it involves.
  • Action is the IDEA plugin used to configure the window event entry, and to configure the action under the button and corresponding shortcut key.

2. Code protocol scan (AliInspectionAction)

class AliInspectionAction : AnAction(a){

    override fun actionPerformed(e: AnActionEvent) { val project = e.project ? :return
        val analysisUIOptions = ServiceManager.getService(project, AnalysisUIOptions::class.java)!!
        analysisUIOptions.GROUP_BY_SEVERITY = true

        val managerEx = InspectionManager.getInstance(project) as InspectionManagerEx
        val toolWrappers = Inspections.aliInspections(project) {
            it.tool is AliBaseInspection
        }
        val psiElement = e.getData<PsiElement>(CommonDataKeys.PSI_ELEMENT)
        val psiFile = e.getData<PsiFile>(CommonDataKeys.PSI_FILE)
        val virtualFile = e.getData<VirtualFile>(CommonDataKeys.VIRTUAL_FILE)
        
		...
		
		createContext(
    	toolWrappers, managerEx, element,
    	projectDir, analysisScope
		).doInspections(analysisScope)
}		
Copy the code
  • This is a plug-in code logic developed based on Kotlin language. It obtains the project information, class information, etc. through the actionPerformed method, and then executes the code to check doconforms

3. The statute p3c – PMD

When we read further down the page, we see something about PMD. PMD is a Java program static code inspection tool issued by BSD protocol. When using PMD rules to analyze Java source code, PMD first uses JavaCC and EBNF grammar to generate a parser, which is used to analyze Java code in the form of ordinary text and generate grammar in line with a specific grammar structure. At the same time, on the basis of JavaCC, the concept of semantics is added, namely JJTree. Through a transformation of JJTree, the Java code is transformed into an AST, which is the semantic layer above the Java symbol flow. PMD processes the AST into a symbol table. Then you write PMD rules, a PMD rule can be thought of as a Visitor that walks through the AST to find a particular pattern between multiple objects, the problem with the code. The software has powerful functions and high scanning efficiency. It is a good helper for Java programmer debug.

So what is P3C-PMD?

ViolationUtils.addViolationWithPrecisePosition(this, node, data,
    I18nResources.getMessage("java.naming.ClassNamingShouldBeCamelRule.violation.msg",
        node.getImage()));
Copy the code
  • The P3C-PMD plug-in is implemented based on PMD, and more specifically pmD-Java, because PMD supports not only Java code analysis, but also many other languages.
  • The way to customize rules is through custom Java classes and XPATH rules.

4. Statute monitoring cases

Be reasonable, say ten thousand thousand, still have to come up with the code to run, just know what PMD is like.

1. Test engineering

Guide - PMD └ ─ ─ the SRC ├ ─ ─ the main │ ├ ─ ─ Java │ │ └ ─ ─ cn. Itedus. Guide. PMD. Rule │ │ ├ ─ ─ naming │ │ │ ├ ─ ─ ClassNamingShouldBeCamelRule. Java │ │ │ ├ ─ ─ ConstantFieldShouldBeUpperCaseRule. Java │ │ │ └ ─ ─ LowerCamelCaseVariableNamingRule. Java │ │ ├ ─ ─ utils │ │ │ ├ ─ ─ StringAndCharConstants. Java │ │ │ └ ─ ─ ViolationUtils. Java │ ├── ├─ ├─ ├─ ├─ ├─ ├─ ├─ ├─ namelist The test └ ─ ─ Java └ ─ ─ cn. Itedus. Demo. Test ├ ─ ─ ApiTest. Java └ ─ ─ TErrDto. JavaCopy the code
  • Source: github.com/fuzhengwei/…

This is a test project similar to P3C-PMD that handles its own code review criteria by extending the rewrite code monitoring protocol.

  • Naming a class is used to handle naming related rules, class name, attribute name, method name, etc
  • Ali-naming. XML under Resources is the configuration file of the protocol

2. Hump naming convention

public class ClassNamingShouldBeCamelRule extends AbstractJavaRule {

    private static final Pattern PATTERN
            = Pattern.compile("^I? ([A-Z][a-z0-9]+)+(([A-Z])|(DO|DTO|VO|DAO|BO|DAOImpl|YunOS|AO|PO))? $");

    @Override
    public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
        if (PATTERN.matcher(node.getImage()).matches()) {
            return super.visit(node, data);
        }
        
        ViolationUtils.addViolationWithPrecisePosition(this, node, data,
                I18nResources.getMessage("java.naming.ClassNamingShouldBeCamelRule.violation.msg",
                        node.getImage()));

        return super.visit(node, data); }}Copy the code
  • The visit method is overridden by inherits the AbstractJavaRule class provided by PMD and validates in a regular manner.
  • Visit method entry type is very many, respectively used to deal with the class, interface, method, code and other contents of the monitoring process, as long as the rewrite of the required method, in which their own processing can be.
  • ClassNamingShouldBeCamelRule, ConstantFieldShouldBeUpperCaseRule, LowerCamelCaseVariableNamingRule three classes have similar function, here not show one by one, You can refer directly to the source code.

3. Ali – naming. XML configuration

<rule name="ClassNamingShouldBeCamelRule"
      language="java"
      since="1.6"
      message="java.naming.ClassNamingShouldBeCamelRule.rule.msg"
      class="cn.itedus.guide.pmd.rule.naming.ClassNamingShouldBeCamelRule">
    <priority>3</priority>
</rule>
Copy the code
  • In ali-naming. XML, it is used to configure the protocol processing class, priority level, and message alert text.
  • You can also configure code examples to use<example>Tag, in which to write standard code.

4. Test the validation protocol

Sample problem classes

public class TErrDto {

    public static final Long max = 50000L;

    public void QueryUserInfo(a){
        boolean baz = true;
        while (baz)
            baz = false; }}Copy the code

Unit testing

@Test
public void test_naming(a){
    String[] str = {
            "-d"."E:\\itstack\\git\\github.com\\guide-pmd\\src\\test\\java\\cn\\itedus\\demo\\test\\TErrDto.java"."-f"."text"."-R"."E:\\itstack\\git\\github.com\\guide-pmd\\src\\main\\resources\\rule\\ali-naming.xml"
            // "category/java/codestyle.xml"
    };
    PMD.main(str);
}
Copy the code
  • Test validation of the protocol can be done directly using the pmD. main method, which provides string array inputs, where the code monitors the address and the protocol configuration needs to be absolute paths.

The test results

TErrDto.java:3[TErrDto] does not comply with UpperCamelCase naming style terrdto. Java:5Names should be all uppercase and delimited with an underscore:7: Method name [QueryUserInfo] does not match lowerCamelCase naming style Process finished with exit code4
Copy the code
  • As can be seen from the test results, the three code conventions we wrote detected the code naming style, constant capitalization, and method name not conforming to the hump logo respectively.
  • You can also testcategory/java/codestyle.xmlThis is good protocol monitoring provided by PMD itself.

Five, expand understanding Sonar

In fact, with PMD static code inspection protocol, can do a lot of things, not only to the code is being written to check, but also to the different stages of the code analysis and risk reminder, such as: ready to test stage, has been completed online, can do the corresponding monitoring processing.

Sonar is one such tool, it is a Web system that can present the results of static code scanning, the results can be customized, support for multiple languages is its extensibility. www.sonarqube.org/

  • Not following code standards: Sonar can regulate code writing with code rule checking tools like PMD,CheckStyle,Findbugs, and more.
  • Potential bugs: Sonar can detect potential bugs with code rule detection tools like PMD,CheckStyle,Findbugs, and more.
  • Poor complexity distribution: files, classes, methods, etc., will be hard to change if their complexity is too high, making them difficult for developers to understand, and without automated unit testing, changes to any component in the program will likely result in the need for full regression testing.
  • Duplication: Obviously programs that contain a lot of copy-and-paste code are of poor quality, sonar can show you where the source code is heavily duplicated.
  • Insufficient or Too many comments: No comments make code less readable, especially when staff changes inevitably occur, and too many comments cause developers to spend too much time reading comments, which defeats the purpose.
  • Lack of unit tests: Sonar can easily tally up and show unit test coverage.
  • Bad design: Sonar can find loops, show package to package, class to class interdependencies, detect custom architecture rules manage third-party JAR packages, LCOM4 can detect the application of individual task rules, detect coupling.
  • Improve code quality: Understand your coding mistakes to make your code more readable and maintainable.

Six, summarized

  • PMD is a code inspection tool that uses the BSD protocol. You can extend the implementation to your own standards and specifications as well as perfect personalized reminders and fixes.
  • In addition, the code inspection based on IDEA plug-in or the processing of audit requirements can also be extended based on IDEA plug-in, such as reminding repair, providing repair operations, and checking its own business logic. For example, momO open source library under an IDEA static code security audit and vulnerability one-click repair plug-in github.com/momosecurit…
  • As a bonus, The Kotlin language can be converted to Java in IDEA, so you can convert and read code like this if it is not easy to understand. In addition, IDEA plug-in development needs to be created based on the template provided by Gradle or itself. If you are interested, you can also read the article I wrote on IDEA plug-in development.

Seven, series recommendation

  • Automatic analysis of r&d delivery quality is realized based on IDEA plug-in development and bytecode staking technology
  • Technical research, IDEA plug-in how to develop “scaffolding, low code visual orchestration, interface generation test”?
  • SpringBoot Middleware Design and Development
  • Note taking: Summary of technical architecture coverage and evolution process
  • Add some practice to your learning and develop a distributed IM system!