private void replaceIteratorNext( PsiElement element, String contentVariableName, String iteratorName, PsiElement childToSkip, StringBuilder out, PsiType contentType) { if (isIteratorNext(element, iteratorName, contentType)) { out.append(contentVariableName); } else { final PsiElement[] children = element.getChildren(); if (children.length == 0) { final String text = element.getText(); if (PsiKeyword.INSTANCEOF.equals(text) && out.charAt(out.length() - 1) != ' ') { out.append(' '); } out.append(text); } else { boolean skippingWhiteSpace = false; for (final PsiElement child : children) { if (child.equals(childToSkip)) { skippingWhiteSpace = true; } else if (child instanceof PsiWhiteSpace && skippingWhiteSpace) { // don't do anything } else { skippingWhiteSpace = false; replaceIteratorNext( child, contentVariableName, iteratorName, childToSkip, out, contentType); } } } } }
private void replaceCollectionGetAccess( PsiElement element, String contentVariableName, PsiVariable listVariable, String indexName, PsiElement childToSkip, StringBuilder out) { if (isListGetLookup(element, indexName, listVariable)) { out.append(contentVariableName); } else { final PsiElement[] children = element.getChildren(); if (children.length == 0) { final String text = element.getText(); if (PsiKeyword.INSTANCEOF.equals(text) && out.charAt(out.length() - 1) != ' ') { out.append(' '); } out.append(text); } else { boolean skippingWhiteSpace = false; for (final PsiElement child : children) { if (child.equals(childToSkip)) { skippingWhiteSpace = true; } else if (child instanceof PsiWhiteSpace && skippingWhiteSpace) { // don't do anything } else { skippingWhiteSpace = false; replaceCollectionGetAccess( child, contentVariableName, listVariable, indexName, childToSkip, out); } } } } }
private static void generateNameByString( Set<String> possibleNames, String value, NameValidator validator, boolean forStaticVariable, Project project) { if (!JavaPsiFacade.getInstance(project).getNameHelper().isIdentifier(value)) return; if (forStaticVariable) { StringBuilder buffer = new StringBuilder(value.length() + 10); char[] chars = new char[value.length()]; value.getChars(0, value.length(), chars, 0); boolean wasLow = Character.isLowerCase(chars[0]); buffer.append(Character.toUpperCase(chars[0])); for (int i = 1; i < chars.length; i++) { if (Character.isUpperCase(chars[i])) { if (wasLow) { buffer.append('_'); wasLow = false; } } else { wasLow = true; } buffer.append(Character.toUpperCase(chars[i])); } possibleNames.add(validator.validateName(buffer.toString(), true)); } else { possibleNames.add(validator.validateName(value, true)); } }
private static void appendInferredType( PsiElement originalElement, GrVariable variable, StringBuilder buffer) { PsiType inferredType = null; if (PsiImplUtil.isWhiteSpaceOrNls(originalElement)) { originalElement = PsiTreeUtil.prevLeaf(originalElement); } if (originalElement != null && originalElement.getNode().getElementType() == GroovyTokenTypes.mIDENT) { originalElement = originalElement.getParent(); } if (originalElement instanceof GrReferenceExpression) { inferredType = ((GrReferenceExpression) originalElement).getType(); } else if (originalElement instanceof GrVariableDeclaration) { inferredType = variable.getTypeGroovy(); } else if (originalElement instanceof GrVariable) { inferredType = ((GrVariable) originalElement).getTypeGroovy(); } if (inferredType != null) { buffer.append("[inferred type] "); appendTypeString(buffer, inferredType, originalElement); } else { buffer.append("[cannot infer type]"); } }
private static void generateVariableInfo( PsiElement originalElement, StringBuilder buffer, PsiVariable variable) { if (variable instanceof PsiField) { final PsiClass parentClass = ((PsiField) variable).getContainingClass(); if (parentClass != null) { buffer.append(JavaDocUtil.getShortestClassName(parentClass, variable)); newLine(buffer); } generateModifiers(buffer, variable); } final PsiType type = variable instanceof GrVariable ? ((GrVariable) variable).getDeclaredType() : variable.getType(); PsiImplUtil.appendTypeString( buffer, calcSubstitutor(originalElement).substitute(type), originalElement); buffer.append(" "); buffer.append(variable.getName()); if (variable instanceof GrVariable) { newLine(buffer); while (originalElement != null) { PsiReference ref = originalElement.getReference(); if (ref != null && ref.resolve() != null) break; originalElement = originalElement.getParent(); } if (originalElement != null) { appendInferredType(originalElement, (GrVariable) variable, buffer); } } }
public void emit(Emitter emitter) { StringBuilder sb = emitter.getTextBuffer(); if (getCustomizedPrecedingComment().length() > 0) { sb.append("\n"); sb.append(getCustomizedPrecedingComment()); } emitAllElements(sb, emitter.getDocument()); if (getCustomizedTrailingComment().length() > 0) { sb.append("\n"); sb.append(getCustomizedTrailingComment()); } /** emit corresponding setter, overloaded methods, and related methods, if any. */ ListIterator li; if (isGetter()) { for (MethodEntry entry : myCorrespondingGetterSetters) { entry.emit(emitter); } } for (MethodEntry me : myOverloadedMethods) { me.emit(emitter); } for (MethodEntry me : sortedMethods) { me.emit(emitter); } }
public String calcGenerics(@NotNull PsiElement context, InsertionContext insertionContext) { if (insertionContext.getCompletionChar() == '<') { return ""; } assert context.isValid(); if (myDiamond) { return "<>"; } if (getObject() instanceof PsiClass) { PsiClass psiClass = (PsiClass) getObject(); PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(psiClass.getProject()).getResolveHelper(); PsiSubstitutor substitutor = getSubstitutor(); StringBuilder builder = new StringBuilder(); for (PsiTypeParameter parameter : psiClass.getTypeParameters()) { PsiType substitute = substitutor.substitute(parameter); if (substitute == null || (PsiUtil.resolveClassInType(substitute) == parameter && resolveHelper.resolveReferencedClass(parameter.getName(), context) != CompletionUtil.getOriginalOrSelf(parameter))) { return ""; } if (builder.length() > 0) { builder.append(", "); } builder.append(substitute.getCanonicalText()); } if (builder.length() > 0) { return "<" + builder + ">"; } } return ""; }
@Override public String getEventMessage(LocatableEvent event) { final Location location = event.location(); String sourceName; try { sourceName = location.sourceName(); } catch (AbsentInformationException e) { sourceName = getFileName(); } final boolean printFullTrace = Registry.is("debugger.breakpoint.message.full.trace"); StringBuilder builder = new StringBuilder(); if (printFullTrace) { builder.append( DebuggerBundle.message( "status.line.breakpoint.reached.full.trace", DebuggerUtilsEx.getLocationMethodQName(location))); try { final List<StackFrame> frames = event.thread().frames(); renderTrace(frames, builder); } catch (IncompatibleThreadStateException e) { builder.append("Stacktrace not available: ").append(e.getMessage()); } } else { builder.append( DebuggerBundle.message( "status.line.breakpoint.reached", DebuggerUtilsEx.getLocationMethodQName(location), sourceName, getLineIndex() + 1)); } return builder.toString(); }
/** * Returns the original comment info of the specified element or null * * @param element the specified element * @return text chunk */ @Nullable private static String getOrigCommentInfo(PsiDocCommentOwner element) { StringBuilder sb = new StringBuilder(); PsiElement e = element.getFirstChild(); if (!(e instanceof PsiComment)) { // no comments for this element return null; } else { boolean first = true; while (true) { if (e instanceof PsiDocComment) { PsiComment cm = (PsiComment) e; String text = cm.getText(); if (text.startsWith("//")) { if (!first) sb.append('\n'); sb.append(text.substring(2).trim()); } else if (text.startsWith("/*")) { if (text.charAt(2) == '*') { text = text.substring(3, Math.max(3, text.length() - 2)); } else { text = text.substring(2, Math.max(2, text.length() - 2)); } sb.append(text); } } else if (!(e instanceof PsiWhiteSpace) && !(e instanceof PsiComment)) { break; } first = false; e = e.getNextSibling(); } return sb.toString(); } }
private static String genIteratorVar( GrVariableDeclaration variableDeclaration, StringBuilder builder, ExpressionContext expressionContext, @NotNull GrExpression tupleInitializer, PsiType iteratorType, GroovyResolveResult iteratorMethodResult) { final String iteratorName = suggestVarName(iteratorType, variableDeclaration, expressionContext); builder.append("final "); writeType(builder, iteratorType, variableDeclaration); builder.append(' ').append(iteratorName).append(" = "); invokeMethodByResolveResult( tupleInitializer, iteratorMethodResult, "iterator", GrExpression.EMPTY_ARRAY, GrNamedArgument.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY, new ExpressionGenerator(builder, expressionContext), variableDeclaration); builder.append(";\n"); return iteratorName; }
public static String getUnescapedText( PsiFile file, @Nullable final PsiElement startElement, @Nullable final PsiElement endElement) { final InjectedLanguageManager manager = InjectedLanguageManager.getInstance(file.getProject()); if (manager.getInjectionHost(file) == null) { return file.getText() .substring( startElement == null ? 0 : startElement.getTextRange().getStartOffset(), endElement == null ? file.getTextLength() : endElement.getTextRange().getStartOffset()); } final StringBuilder sb = new StringBuilder(); file.accept( new PsiRecursiveElementWalkingVisitor() { Boolean myState = startElement == null ? Boolean.TRUE : null; @Override public void visitElement(PsiElement element) { if (element == startElement) myState = Boolean.TRUE; if (element == endElement) myState = Boolean.FALSE; if (Boolean.FALSE == myState) return; if (Boolean.TRUE == myState && element.getFirstChild() == null) { sb.append(getUnescapedLeafText(element, false)); } else { super.visitElement(element); } } }); return sb.toString(); }
private void suggestNamesFromGenericParameters( final PsiType type, final VariableKind variableKind, final Collection<String> suggestions, boolean correctKeywords) { if (!(type instanceof PsiClassType)) { return; } StringBuilder fullNameBuilder = new StringBuilder(); final PsiType[] parameters = ((PsiClassType) type).getParameters(); for (PsiType parameter : parameters) { if (parameter instanceof PsiClassType) { final String typeName = normalizeTypeName(getTypeName(parameter)); if (typeName != null) { fullNameBuilder.append(typeName); } } } String baseName = normalizeTypeName(getTypeName(type)); if (baseName != null) { fullNameBuilder.append(baseName); ContainerUtil.addAll( suggestions, getSuggestionsByName(fullNameBuilder.toString(), variableKind, false, correctKeywords)); } }
public static String getQualifiedReferenceText(PbRef ref) { StringBuilder sbuilder = new StringBuilder(); if (!appendName(ref, sbuilder)) { return null; } return sbuilder.toString(); }
@Override public String variableNameToPropertyName(String name, VariableKind variableKind) { if (variableKind == VariableKind.STATIC_FINAL_FIELD || variableKind == VariableKind.STATIC_FIELD && name.contains("_")) { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (c != '_') { if (Character.isLowerCase(c)) { return variableNameToPropertyNameInner(name, variableKind); } buffer.append(Character.toLowerCase(c)); continue; } //noinspection AssignmentToForLoopParameter i++; if (i < name.length()) { c = name.charAt(i); buffer.append(c); } } return buffer.toString(); } return variableNameToPropertyNameInner(name, variableKind); }
@Nullable private Pair<String, String> parseAttribute() { ZenCodingToken token = nextToken(); if (!(token instanceof IdentifierToken)) { return null; } final String name = ((IdentifierToken) token).getText(); myIndex++; token = nextToken(); if (token != ZenCodingTokens.EQ) { return new Pair<String, String>(name, ""); } myIndex++; final StringBuilder attrValueBuilder = new StringBuilder(); String value; do { token = nextToken(); value = token != null && token == ZenCodingTokens.SHARP ? token.toString() : getAttributeValueByToken(token); if (value != null) { attrValueBuilder.append(value); myIndex++; } } while (value != null); return new Pair<String, String>(name, attrValueBuilder.toString()); }
@Override public void visitEnd() { if (hasParams && myDesc != null) { myBuilder.append(')'); } myCallback.callback(myBuilder.toString()); }
private static void appendElementText( @NotNull PsiElement element, @NotNull PsiElement elementToReplace, @Nullable PsiExpression replacementExpression, @NotNull StringBuilder out) { if (element.equals(elementToReplace)) { final String replacementText = (replacementExpression == null) ? "" : replacementExpression.getText(); out.append(replacementText); return; } final PsiElement[] children = element.getChildren(); if (children.length == 0) { out.append(element.getText()); if (element instanceof PsiComment) { final PsiComment comment = (PsiComment) element; final IElementType tokenType = comment.getTokenType(); if (tokenType == JavaTokenType.END_OF_LINE_COMMENT) { out.append('\n'); } } return; } for (PsiElement child : children) { appendElementText(child, elementToReplace, replacementExpression, out); } }
private static void genForPart( StringBuilder builder, GroovyPsiElement part, final Generator visitor) { part.accept(visitor); for (String statement : visitor.getContext().myStatements) { builder.append(statement).append(", "); } builder.append(visitor.getBuilder()); }
private static String constantValueToConstantName(final String[] names) { final StringBuilder result = new StringBuilder(); for (int i = 0; i < names.length; i++) { if (i > 0) result.append("_"); result.append(names[i]); } return result.toString(); }
private static void createElementLink( @NonNls final StringBuilder sb, final PsiElement element, final String str) { sb.append(" <a href=\"psi_element://"); sb.append(JavaDocUtil.getReferenceText(element.getProject(), element)); sb.append("\">"); sb.append(str); sb.append("</a>"); sb.append("<br>"); }
private static String stripSpaces(String text) { String[] lines = LineTokenizer.tokenize(text.toCharArray(), false); StringBuilder buf = new StringBuilder(text.length()); for (int i = 0; i < lines.length; i++) { if (i > 0) buf.append('\n'); buf.append(rTrim(lines[i])); } return buf.toString(); }
private static void generateModifiers(StringBuilder buffer, PsiElement element) { String modifiers = PsiFormatUtil.formatModifiers(element, PsiFormatUtilBase.JAVADOC_MODIFIERS_ONLY); if (!modifiers.isEmpty()) { buffer.append(modifiers); buffer.append(" "); } }
public static String getLocationMethodQName(@NotNull Location location) { StringBuilder res = new StringBuilder(); ReferenceType type = location.declaringType(); if (type != null) { res.append(type.name()).append('.'); } res.append(location.method().name()); return res.toString(); }
@Override public String getPresentableText() { if (myPresentableText == null) { StringBuilder buffer = new StringBuilder(); buildText(myClass, mySubstitutor, buffer, false, false); myPresentableText = buffer.toString(); } return myPresentableText; }
@Override public void visitFlowInterruptStatement(GrFlowInterruptingStatement statement) { builder.append(statement.getStatementText()); final String name = statement.getLabelName(); if (name != null) { builder.append(' ').append(name); // todo check incorrect labels } builder.append(';'); }
@Override public String getInternalCanonicalText() { if (myInternalCanonicalText == null) { StringBuilder buffer = new StringBuilder(); buildText(myClass, mySubstitutor, buffer, true, true); myInternalCanonicalText = buffer.toString(); } return myInternalCanonicalText; }
private static void generateTraitType( @NotNull StringBuilder buffer, @NotNull GrTraitType type, PsiElement context) { appendTypeString(buffer, type.getExprType(), context); buffer.append(" as "); for (PsiType traitType : type.getTraitTypes()) { appendTypeString(buffer, traitType, context); buffer.append(", "); } buffer.delete(buffer.length() - 2, buffer.length()); }
@Override public String getCanonicalText() { if (myCanonicalText == null) { assert mySubstitutor.isValid(); StringBuilder buffer = new StringBuilder(); buildText(myClass, mySubstitutor, buffer, true, false); myCanonicalText = buffer.toString(); } return myCanonicalText; }
private static String buildAnnotationText(PsiAnnotation annotation) { final StringBuilder out = new StringBuilder("@"); final PsiJavaCodeReferenceElement nameReferenceElement = annotation.getNameReferenceElement(); assert nameReferenceElement != null; out.append(nameReferenceElement.getText()); final PsiAnnotationParameterList parameterList = annotation.getParameterList(); final PsiNameValuePair[] attributes = parameterList.getAttributes(); if (attributes.length == 0) { return out.toString(); } out.append('('); if (attributes.length == 1) { final PsiNameValuePair attribute = attributes[0]; @NonNls final String name = attribute.getName(); if (name != null && !PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME.equals(name)) { out.append(name).append('='); } buildAttributeValueText(attribute.getValue(), out); } else { for (int i = 0; i < attributes.length; i++) { final PsiNameValuePair attribute = attributes[i]; if (i > 0) { out.append(','); } out.append(attribute.getName()).append('='); buildAttributeValueText(attribute.getValue(), out); } } out.append(')'); return out.toString(); }
public static String fixSignature(final String signature, final boolean parameterNames) { @NonNls final StringBuilder sb = new StringBuilder(); final StringTokenizer st = new StringTokenizer(signature, "(,)"); //noinspection ForLoopThatDoesntUseLoopVariable for (int i = 0; st.hasMoreTokens(); i++) { final String token = st.nextToken().trim(); if (i > 1) sb.append(", "); final int idx; if (i == 0) { sb.append(token).append("("); } else if ((idx = token.indexOf(' ')) > -1) { if (parameterNames) { sb.append(token); } else { sb.append(token.substring(0, idx)); } } else { sb.append(token); if (parameterNames) { sb.append(' ').append('p').append(i); } } } sb.append(")"); return sb.toString(); }