001/*
002 * Copyright (c) 2009 The openGion Project.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *        http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
013 * either express or implied. See the License for the specific language
014 * governing permissions and limitations under the License.
015 */
016package org.opengion.fukurou.taglet2;
017
018
019import jdk.javadoc.doclet.DocletEnvironment      ;
020// import jdk.javadoc.doclet.Doclet  ;
021// import jdk.javadoc.doclet.Reporter ;
022// import javax.lang.model.element.Element      ;
023import javax.lang.model.element.Modifier ;
024import javax.lang.model.element.TypeElement;
025// import javax.lang.model.element.ElementKind  ;
026// import javax.lang.model.element.VariableElement;
027import javax.lang.model.element.ExecutableElement;
028// import javax.lang.model.SourceVersion ;
029import javax.lang.model.type.TypeMirror;
030import javax.lang.model.type.TypeKind;
031import javax.lang.model.util.ElementFilter ;
032import javax.lang.model.util.Elements ;
033import javax.tools.Diagnostic.Kind ;
034import com.sun.source.doctree.DocCommentTree  ;
035import com.sun.source.util.DocTrees  ;
036// import com.sun.source.util.DocSourcePositions  ;
037import com.sun.source.doctree.DocTree  ;
038
039
040// import java.util.Locale ;
041import java.util.Set;
042import java.util.Map;
043// import java.util.HashMap;
044import java.util.List;
045import java.util.HashSet;
046import java.util.Arrays;
047// import java.util.stream.Stream;                                                                              // 6.4.3.4 (2016/03/11)
048// import java.util.stream.Collectors;                                                                  // 6.4.3.4 (2016/03/11)
049
050// import java.io.IOException;
051// import java.io.File;
052// import java.io.PrintWriter;
053
054// import org.opengion.fukurou.util.FileUtil;
055// import org.opengion.fukurou.util.StringUtil;
056
057/**
058 * ソースコメントから、パラメータ情報を取り出す Doclet クラスです。
059 * og.paramLevel タグと og.cryptography タグを切り出します。
060 * これらは、システムパラメータとしてGE12テーブルに設定される値をクラスより抽出する
061 * のに使用します。
062 *
063 * @version  7.3
064 * @author      Kazuhiko Hasegawa
065 * @since        JDK11.0,
066 */
067public class DocTreeTaglib extends AbstractDocTree {
068        private static final String OG_FOR_SMPL = "og.formSample";
069        private static final String OG_TAG_NAME = "og.tag";
070        private static final String OG_GROUP    = "og.group";
071
072        private static final String     DOC_PARAM       = "param";              // 6.1.1.0 (2015/01/17)
073
074        private static final String OG_TAG_CLASS = "org.opengion.hayabusa.taglib";
075
076        private String  version         ;
077        private String  outfile         ;
078
079//      private DocTrees docUtil;
080//      private Elements eleUtil ;
081
082        /**
083         * Doclet のエントリポイントメソッドです(昔の startメソッド)。
084         *
085         * @og.rev 7.3.0.0 (2021/01/06) 新しいJavaDoc対応
086         *
087         * @param docEnv ドックレットを1回呼び出す操作環境
088         *
089         * @return 正常実行時 true
090         */
091        @Override
092        public boolean run( final DocletEnvironment docEnv ) {
093                try( DocTreeWriter writer = new DocTreeWriter( outfile,ENCODE ) ) {
094                        writer.printTag( "<?xml version=\"1.0\" encoding=\"", ENCODE , "\" ?>" );
095                        writer.printTag( "<javadoc>" );
096                        writer.printTag( "  <version>",version,"</version>" );
097                        writer.printTag( "  <description></description>" );
098                        writeContents( docEnv,writer );
099                        writer.printTag( "</javadoc>" );
100                }
101                catch( final Throwable th ) {
102                        reporter.print(Kind.ERROR, th.getMessage());
103                }
104
105                return true;
106        }
107
108        /**
109         * DocletEnvironmentよりコンテンツを作成します。
110         *
111         * @og.rev 7.3.0.0 (2021/01/06) 新しいJavaDoc対応
112         *
113         * @param docEnv        ドックレットの最上位
114         * @param writer        DocTreeWriterオブジェクト
115         */
116        private void writeContents( final DocletEnvironment docEnv, final DocTreeWriter writer ) {
117//              docUtil = docEnv.getDocTrees();
118//              eleUtil = docEnv.getElementUtils();
119
120//              // get the DocTrees utility class to access document comments
121                final DocTrees docUtil = docEnv.getDocTrees();
122                final Elements eleUtil  = docEnv.getElementUtils();
123
124                final Set<String> mtdClsSet = new HashSet<>();                  //  6.4.3.1 (2016/02/12) 変数名も変えておきます。
125
126                // クラス単位にループする。
127                for( final TypeElement typEle : ElementFilter.typesIn(docEnv.getIncludedElements())) {
128                        final String fullName   = String.valueOf( typEle.getQualifiedName() ) ;
129//                      final String fullName = String.valueOf( typEle ) ;
130                        writer.setClassName( fullName );
131
132                        if( !typEle.getModifiers().contains( Modifier.PUBLIC ) ||
133                                !fullName.contains( OG_TAG_CLASS ) ) { continue; }              // public かつ taglib に絞る
134
135                        final DocCommentTree docTree = docUtil.getDocCommentTree(typEle);               // ドキュメンテーション・コメントが見つからない場合、null が返る。
136
137                        final List<? extends DocTree> desc      = docTree == null ? EMPTY_LIST : docTree.getFirstSentence();
138                        final List<? extends DocTree> cmnt      = docTree == null ? EMPTY_LIST : docTree.getFullBody();
139
140                        final Map<String,List<String>> blkTagMap = blockTagsMap(docTree);
141                        final String smplTags   = getBlockTag( OG_FOR_SMPL, blkTagMap, ""  );
142                        final String grpTags    = getBlockTag( OG_GROUP   , blkTagMap, "," );
143
144//                      String smplTags         = "";
145//                      final StringBuilder grpBuf = new StringBuilder();
146//                      if( docTree != null ) {
147//                              for( final DocTree dt : docTree.getBlockTags() ) {
148//                                      final String tag = String.valueOf(dt);
149//                                      if(      tag.contains( OG_FOR_SMPL      ) ) { smplTags  = cutTag( tag,OG_FOR_SMPL       ); }
150//                                      else if( tag.contains( OG_GROUP         ) ) { grpBuf.append( '【' ).append( cutTag( tag,OG_GROUP ) ).append( "】," ); }
151//                              }
152//                      }
153//                      final String grpTags = grpBuf.length() == 0 ? "" : grpBuf.substring(0,grpBuf.length()-1);       // 最後のカンマを削除
154
155                        // 5.7.1.1 (2013/12/13) タグのインデントを止める。
156                        writer.printTag( "<classDoc>" );
157                        writer.printTag( "  <tagClass>"         ,fullName       ,"</tagClass>"          );
158                        writer.printTag( "  <tagGroup>"         ,grpTags        ,"</tagGroup>"          );
159                        writer.printTag( "  <description>"      ,desc           ,"</description>"       );
160                        writer.printTag( "  <contents>"         ,cmnt           ,"</contents>"          );
161                        writer.printTag( "  <formSample>"       ,smplTags       ,"</formSample>"        );
162
163                        mtdClsSet.clear();
164                        String className = String.valueOf( typEle );
165                        TypeElement loopEle = typEle;
166                        while(  loopEle != null                                         &&
167                                        className.contains( OG_TAG_CLASS ) ) {
168
169                                writer.setClassName( className );
170                                final String extendFlag = String.valueOf( className.contains( "HTMLTagSupport" ) );
171
172                                // メソッドのみフィルタリングして取得する
173                                for( final ExecutableElement ele : ElementFilter.methodsIn(loopEle.getEnclosedElements())) {            // メソッドだけに絞る
174                                        if( !ele.getModifiers().contains( Modifier.PUBLIC ) ) { continue; }                                             // public だけに絞る
175
176                                        final DocCommentTree mdoc = docUtil.getDocCommentTree(ele);             // ドキュメンテーション・コメントが見つからない場合、null が返る。
177                                        if( mdoc == null ) { continue; }
178
179                                        final Map<String,List<String>> blkTagMap2 = blockTagsMap(mdoc);
180                                        final String tags = getBlockTag( OG_TAG_NAME , blkTagMap2, "" );
181
182//                                      String tags = "";
183//                                      for( final DocTree dt : mdoc.getBlockTags() ) {
184//                                              final String tag = String.valueOf(dt);
185//                                              if( tag.contains( OG_TAG_NAME ) ) { tags = cutTag( tag,OG_TAG_NAME      ); }
186//                                      }
187
188                                        if( !tags.isEmpty() ) {
189                                                final String fname = String.valueOf( ele );
190                                                if( !mtdClsSet.add( fname ) ) { continue; }             // 継承もとに同じメソッド名がある場合は、無視する。
191
192                                                final String methodName = removeSetter( String.valueOf( ele.getSimpleName() ) );
193
194                                                final List<? extends DocTree> ftag      = mdoc.getFirstSentence();
195                                                final List<? extends DocTree> mcmnt     = mdoc.getFullBody();
196                                                final String[] keylblCd = methodLabelCode( mdoc );
197
198//                                              final List<? extends DocTree> doc1      = mdoc.getPostamble();
199//                                              final List<? extends DocTree> doc2      = mdoc.getPreamble();
200
201                                                // 5.7.1.1 (2013/12/13) タグのインデントを止める。
202                                                writer.printTag( "  <method>" );
203                                                writer.printTag( "    <name>"           ,methodName     ,"</name>" );
204                                                writer.printTag( "    <label>"          ,keylblCd[1],"</label>" );              // 6.1.1.0 (2015/01/17)
205                                                writer.printTag( "    <comment>"        ,keylblCd[2],"</comment>" );    // 6.2.5.0 (2015/06/05)
206                                                writer.printTag( "    <code>"           ,keylblCd[3],"</code>" );               // 6.1.1.0 (2015/01/17)
207                                                writer.printTag( "    <htmlExtend>"     ,extendFlag     ,"</htmlExtend>" );
208                                                writer.printTag( "    <description>",ftag               ,"</description>" );
209                                                writer.printTag( "    <contents>"       ,mcmnt          ,"" );
210                                                writer.printTag( ""                                     ,tags           ,"</contents>" );
211                                                writer.printTag( "  </method>");
212                                        }
213                                }
214
215                                final TypeMirror superType      = loopEle.getSuperclass();
216                                className = String.valueOf( superType );
217                                loopEle = null;                                                 // while ループの終了
218                                if( !TypeKind.NONE.equals( superType.getKind() ) ) {
219                                        for( final TypeElement tp : eleUtil.getAllTypeElements(className) ) {
220                                                if( className.equals( String.valueOf(tp) ) ) {
221                                                        loopEle = tp ; break;
222                                                }
223                                        }
224                                }
225                        }
226                        writer.printTag( "</classDoc>" );
227                }
228        }
229
230        /**
231         * セッターメソッドの setXXXX の set を削除し、次の文字を小文字化します。
232         * つまり、セッターメソッドから属性値を推測します。
233         * (超特殊処理)セッターメソッドのset以下2文字目が大文字の場合は、
234         * 1文字目も大文字と考えて小文字化を行いません。
235         * 例えば、setSYS や setUSER など、RequestValueTag.javaに使用するケースです。
236         *
237         * @param target 処理対象となる文字列
238         *
239         * @return オプション文字列
240         */
241        private String removeSetter( final String target ) {
242                if( target != null && target.startsWith( "set" ) ) {
243                        char[] chs = target.toCharArray();
244                        if( chs.length > 4 && !( chs[4] >= 'A' && chs[4] <= 'Z' ) ) {
245                                chs[3] = Character.toLowerCase( chs[3] ) ;
246                        }
247                        return new String( chs,3,chs.length-3 );
248                }
249                return target;
250        }
251
252
253        /**
254         * MethodDocを受け取り、0:パラメータ、1:ラベル、2:コメント、3:コードを文字列配列に入れて返します。
255         *
256         * これは、タグリブのラベルリソース登録時に使用する情報です。
257         * タグリブのローカルルールとして、0:パラメータ 1:ラベル 2:ラベル以降の解説 3:コード
258         * という記述を行う事を前提にしています。
259         *
260         * 0:パラメータは、引数です。メソッド名ではありませんので、ご注意ください。
261         * 1:ラベルは、パラメータの次の空白文字から、次の空白文字、または、"[" までの文字です。
262         * 2:コメントは、ラベル以降の文字列で、コードの記述部分も含みます。
263         * 3:コード は、特別な処理を行います。"[" と "]" 内に記述された内容を取り出します。
264         *
265         * @og.rev 7.3.0.0 (2021/01/06) 新しいJavaDoc対応
266         *
267         * @param       mdoc DocCommentTreeオブジェクト
268         *
269         * @return      0:パラメータ、1:ラベル、2:コメント、3:コードを文字列配列に詰めた値(長さ4の配列)
270         * @og.rtnNotNull
271         */
272        private String[] methodLabelCode( final DocCommentTree mdoc ) {
273                final String[] arys = new String[] { "","","","" } ;    // 後で内容を更新する。
274
275                final Map<String,List<String>> blkTagMap = blockTagsMap(mdoc);
276                final String prmTag = getBlockTag( DOC_PARAM, blkTagMap, "" );
277
278//              String prmTag = "";
279//              for( final DocTree dt : mdoc.getBlockTags() ) {
280//                      final String tag = String.valueOf(dt);
281//                      if( tag.contains( DOC_PARAM ) ) {
282//                              prmTag = cutTag( tag,DOC_PARAM ); break;                // Taglibのsetter は、paramは一つだけのハズ
283//                      }
284//              }
285
286                // 最大3つ と指定しているが、0:パラメータと1:ラベルの2つしか保証されていない。
287                final String[] temp = prmTag.split( "[\\s]+",3 );               // 空白文字で3つに分解する。
288                System.arraycopy( temp,0,arys,0,temp.length );                  // 6.3.6.0 (2015/08/16)
289
290                // 3:コード があれば、2:コメントから取り出す。
291                final int st1 = arys[2].indexOf( '[' );
292                if( st1 >= 0 ) {
293                        final int st2 = arys[2].indexOf( ']',st1 );
294                        if( st2 > 0 ) {
295                                // 前後の [] は、取り除き、'/' があれば、' ' に置換する。(コード文字列化)
296                                arys[3] = arys[2].substring( st1+1,st2 ).replace( '/' , ' ' );
297                        }
298                }
299
300                return arys ;
301        }
302
303        /**
304         * サポートされているすべてのオプションを返します。
305         *
306         * @return サポートされているすべてのオプションを含むセット、存在しない場合は空のセット
307         */
308        @Override
309        public Set<? extends Option> getSupportedOptions() {
310                final Option[] options = {
311                        new AbstractOption( "-outfile", "-version" ) {
312
313                                /**
314                                 * 必要に応じてオプションと引数を処理します。
315                                 *
316                                 * @param  opt オプション名
317                                 * @param  arguments 引数をカプセル化したリスト
318                                 * @return 操作が成功した場合はtrue、そうでない場合はfalse
319                                 */
320                                @Override
321                                public boolean process(final String opt, final List<String> arguments) {
322                                        if( "-outfile".equalsIgnoreCase(opt) ) {
323                                                outfile = arguments.get(0);
324                                        }
325                                        else if( "-version".equalsIgnoreCase(opt) ) {
326                                                version = arguments.get(0);
327                                        }
328                                        return true;
329                                }
330                        }
331                };
332                return new HashSet<>(Arrays.asList(options));
333        }
334}