Home | History | Annotate | Download | only in processors
      1 /*
      2  * Copyright (C) 2015 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package com.google.currysrc.processors;
     17 
     18 import com.google.common.collect.Lists;
     19 import com.google.currysrc.api.process.Context;
     20 import com.google.currysrc.api.process.Processor;
     21 import com.google.currysrc.api.process.Reporter;
     22 
     23 import org.eclipse.jdt.core.dom.Comment;
     24 import org.eclipse.jdt.core.dom.CompilationUnit;
     25 import org.eclipse.jface.text.BadLocationException;
     26 import org.eclipse.jface.text.Document;
     27 
     28 import java.util.List;
     29 
     30 /**
     31  * A base-class for general comment processors. All comments of all types in a
     32  * {@link CompilationUnit} are considered. Subclasses determine whether to make a complete comment
     33  * replacement.
     34  */
     35 public abstract class BaseModifyCommentScanner implements Processor {
     36 
     37   @Override
     38   public final void process(Context context, CompilationUnit cu) {
     39     Document document = context.document();
     40     Reporter reporter = context.reporter();
     41     List<Comment> comments = cu.getCommentList();
     42     try {
     43       for (Comment comment : Lists.reverse(comments)) {
     44         String commentText = document.get(comment.getStartPosition(), comment.getLength());
     45         String newCommentText = processComment(reporter, comment, commentText);
     46         if (newCommentText != null) {
     47           document.replace(comment.getStartPosition(), comment.getLength(), newCommentText);
     48         }
     49       }
     50     } catch (BadLocationException e) {
     51       throw new AssertionError(e);
     52     }
     53   }
     54 
     55   /**
     56    * Generates new text for the comment, or returns {@code null} if there is nothing to change.
     57    * Comments are passed in the reverse order that they appear in source code to ensure that
     58    * document offsets remain valid.
     59    */
     60   protected abstract String processComment(Reporter reporter, Comment commentNode,
     61       String commentText);
     62 }
     63