summaryrefslogtreecommitdiff
path: root/java/java-psi-impl/src/com/intellij/psi/impl/compiled/SignatureParsing.java
blob: bd5f75ece27fd71ec65945dd50d2efdc23d845d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * @author max
 */
package com.intellij.psi.impl.compiled;

import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.CommonClassNames;
import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
import com.intellij.psi.impl.java.stubs.PsiTypeParameterListStub;
import com.intellij.psi.impl.java.stubs.PsiTypeParameterStub;
import com.intellij.psi.impl.java.stubs.impl.PsiTypeParameterListStubImpl;
import com.intellij.psi.impl.java.stubs.impl.PsiTypeParameterStubImpl;
import com.intellij.psi.stubs.StubElement;
import com.intellij.util.ArrayUtil;
import com.intellij.util.cls.ClsFormatException;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.StringRef;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.text.CharacterIterator;
import java.util.List;

@SuppressWarnings({"HardCodedStringLiteral"})
public class SignatureParsing {
  private SignatureParsing() { }

  public static PsiTypeParameterListStub parseTypeParametersDeclaration(CharacterIterator iterator, StubElement parentStub) throws ClsFormatException {
    PsiTypeParameterListStub list = new PsiTypeParameterListStubImpl(parentStub);
    if (iterator.current() == '<') {
      iterator.next();
      while (iterator.current() != '>') {
        parseTypeParameter(iterator, list);
      }
      iterator.next();
    }

    return list;
  }

  private static PsiTypeParameterStub parseTypeParameter(CharacterIterator iterator, PsiTypeParameterListStub parent) throws ClsFormatException {
    StringBuilder name = new StringBuilder();
    while (iterator.current() != ':' && iterator.current() != CharacterIterator.DONE) {
      name.append(iterator.current());
      iterator.next();
    }
    if (iterator.current() == CharacterIterator.DONE) {
      throw new ClsFormatException();
    }

    //todo parse annotations on type param
    PsiTypeParameterStub parameterStub = new PsiTypeParameterStubImpl(parent, StringRef.fromString(name.toString()));

    // postpone list allocation till a second bound is seen; ignore sole Object bound
    List<String> bounds = null;
    boolean jlo = false;
    while (iterator.current() == ':') {
      iterator.next();
      String bound = parseTopLevelClassRefSignature(iterator);
      if (bound == null) continue;
      if (bounds == null) {
        if (CommonClassNames.JAVA_LANG_OBJECT.equals(bound)) {
          jlo = true;
          continue;
        }
        bounds = ContainerUtil.newSmartList();
        if (jlo) {
          bounds.add(CommonClassNames.JAVA_LANG_OBJECT);
        }
      }
      bounds.add(bound);
    }

    StubBuildingVisitor.newReferenceList(JavaStubElementTypes.EXTENDS_BOUND_LIST, parameterStub, ArrayUtil.toStringArray(bounds));

    return parameterStub;
  }

  @Nullable
  public static String parseTopLevelClassRefSignature(CharacterIterator signature) throws ClsFormatException {
    if (signature.current() == 'L') {
      return parseParameterizedClassRefSignature(signature);
    }
    if (signature.current() == 'T') {
      return parseTypeVariableRefSignature(signature);
    }
    return null;
  }

  private static String parseTypeVariableRefSignature(CharacterIterator signature) {
    signature.next();
    StringBuilder id = new StringBuilder();
    while (signature.current() != ';' && signature.current() != '>') {
      id.append(signature.current());
      signature.next();
    }

    if (signature.current() == ';') {
      signature.next();
    }

    return id.toString();
  }

  private static String parseParameterizedClassRefSignature(CharacterIterator signature) throws ClsFormatException {
    assert signature.current() == 'L';

    signature.next();
    StringBuffer canonicalText = new StringBuffer();
    while (signature.current() != ';' && signature.current() != CharacterIterator.DONE) {
      switch (signature.current()) {
        case '$':
          if (signature.getIndex() > 0) {
            char previous = signature.previous();
            signature.next();
            boolean standAlone$ = !StringUtil.isJavaIdentifierPart(previous); // /$
            if(standAlone$) {
              canonicalText.append('$');
              break;
            } else if (signature.getIndex() + 1 < signature.getEndIndex()) {
              char next = signature.next();
              signature.previous();
              standAlone$ = !StringUtil.isJavaIdentifierPart(next); // $;
              if(standAlone$) {
                canonicalText.append('$');
                break;
              }
            }
          }
        case '/':
        case '.':
          canonicalText.append('.');
          break;
        case '<':
          canonicalText.append('<');
          signature.next();
          do {
            processTypeArgument(signature, canonicalText);
          }
          while (signature.current() != '>');
          canonicalText.append('>');
          break;
        case ' ':
          break;
        default:
          canonicalText.append(signature.current());
      }
      signature.next();
    }

    if (signature.current() == CharacterIterator.DONE) {
      throw new ClsFormatException();
    }

    for (int index = 0; index < canonicalText.length(); index++) {
      final char c = canonicalText.charAt(index);
      if ('0' <= c && c <= '1') {
        if (index > 0 && canonicalText.charAt(index - 1) == '.') {
          canonicalText.setCharAt(index - 1, '$');
        }
      }
    }

    signature.next();

    return canonicalText.toString();
  }

  private static void processTypeArgument(CharacterIterator signature, StringBuffer canonicalText) throws ClsFormatException {
    String typeArgument = parseClassOrTypeVariableElement(signature);
    canonicalText.append(typeArgument);
    if (signature.current() != '>') {
      canonicalText.append(',');
    }
  }

  public static String parseClassOrTypeVariableElement(CharacterIterator signature) throws ClsFormatException {
    char variance = parseVariance(signature);
    if (variance == '*') {
      return decorateTypeText("*", variance);
    }

    int arrayCount = 0;
    while (signature.current() == '[') {
      arrayCount++;
      signature.next();
    }

    final String type = parseTypeWithoutVariance(signature);
    if (type != null) {
      String ref = type;
      while (arrayCount > 0) {
        ref += "[]";
        arrayCount--;
      }
      return decorateTypeText(ref, variance);
    }
    else {
      throw new ClsFormatException();
    }
  }

  private static final char VARIANCE_NONE = '\0';
  private static final char VARIANCE_EXTENDS = '+';
  private static final char VARIANCE_SUPER = '-';
  private static final char VARIANCE_INVARIANT = '*';
  @NonNls private static final String VARIANCE_EXTENDS_PREFIX = "? extends ";
  @NonNls private static final String VARIANCE_SUPER_PREFIX = "? super ";

  private static String decorateTypeText(final String canonical, final char variance) {
    switch (variance) {
      case VARIANCE_NONE:
        return canonical;
      case VARIANCE_EXTENDS:
        return VARIANCE_EXTENDS_PREFIX + canonical;
      case VARIANCE_SUPER:
        return VARIANCE_SUPER_PREFIX + canonical;
      case VARIANCE_INVARIANT:
        return "?";
      default:
        assert false : "unknown variance";
        return null;
    }
  }

  private static char parseVariance(CharacterIterator signature) {
    char variance;
    switch (signature.current()) {
      case '+':
      case '-':
      case '*':
        variance = signature.current();
        signature.next();
        break;
      case '.':
      case '=':
        signature.next();
        // fall through
      default:
        variance = '\0';
    }

    return variance;
  }

  @NotNull
  public static String parseTypeString(@NotNull CharacterIterator signature) throws ClsFormatException {
    int arrayDimensions = 0;
    while (signature.current() == '[') {
      arrayDimensions++;
      signature.next();
    }

    char variance = parseVariance(signature);
    @NonNls String text = parseTypeWithoutVariance(signature);
    if (text == null) throw new ClsFormatException();

    for (int i = 0; i < arrayDimensions; i++) text += "[]";
    if (variance != '\0') {
      text = variance + text;
    }
    return text;
  }

  @Nullable
  private static String parseTypeWithoutVariance(final CharacterIterator signature) throws ClsFormatException {
    final String text;
    switch (signature.current()) {

      case 'L':
        text = parseParameterizedClassRefSignature(signature);
        break;

      case 'T':
        text = parseTypeVariableRefSignature(signature);
        break;

      case 'B':
        text = "byte";
        signature.next();
        break;

      case 'C':
        text = "char";
        signature.next();
        break;

      case 'D':
        text = "double";
        signature.next();
        break;

      case 'F':
        text = "float";
        signature.next();
        break;

      case 'I':
        text = "int";
        signature.next();
        break;

      case 'J':
        text = "long";
        signature.next();
        break;

      case 'S':
        text = "short";
        signature.next();
        break;

      case 'Z':
        text = "boolean";
        signature.next();
        break;

      case 'V':
        text = "void";
        signature.next();
        break;

      default:
        return null;
    }
    return text;
  }
}