diff --git a/jcodemodel/meta/formatter/eclipse/jcodemodel-eclipse-cleanup.xml b/jcodemodel/meta/formatter/eclipse/jcodemodel-eclipse-cleanup.xml index 67be4ebbf..6e8f00ad3 100644 --- a/jcodemodel/meta/formatter/eclipse/jcodemodel-eclipse-cleanup.xml +++ b/jcodemodel/meta/formatter/eclipse/jcodemodel-eclipse-cleanup.xml @@ -1,173 +1,305 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - - - - + + + + + - - - + + + + + + + + + + + + + + + - - + + - - - - - - - + + + + - - - - - - + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + - + + + + + + + + + - - - - - - - - - + + + + + + + - - - - - - - - + - - - - - - + + + + + + + - - + + + + + + + + + - + + + + - - - + - - - - - - - - - - - - - - - + + + + + - - + + + + + + + + + + + + + + - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jcodemodel/meta/formatter/eclipse/jcodemodel-eclipse-formatter.xml b/jcodemodel/meta/formatter/eclipse/jcodemodel-eclipse-formatter.xml index 3bbaf05ae..56c3ea7b0 100644 --- a/jcodemodel/meta/formatter/eclipse/jcodemodel-eclipse-formatter.xml +++ b/jcodemodel/meta/formatter/eclipse/jcodemodel-eclipse-formatter.xml @@ -1,768 +1,405 @@ - - - + + - - - - - - - - - - + + - - - - - - - - - - - - + + - - - - - - - - + + - - - - - - - - - - - - - - - - + - - + - - - - - - - + - - - - - - + - - - - - + - - - - - - - + - - - - - - + - - - - - - + - - - - - - + + - + - - - + - - - - - - - - + - - - - + - - - - - - + - - - - - - - - - - - - + + - - - - + - + - + - - - - - - - - - + + - - - - - + - - - + - - + - - - - - - + - - - - - - - - - + - - - - - - - + - - - + - - - - - - - - - - + + - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - + - - - - - - - - + - - - - - - - - - - + - + + - + - + - - - - - - - - - - - - - + - - - - - - + - - - - - + - - - - - - - - - - + + - - - - + - - - - - - + + + - - - - - - + + - - - - - - - - - + + - - - - - - - - + + + - - - - - - - - - - + + - - - - - - - + - - - - - - - - - - - - + + + - - - - + + - - - + - - - - - - - - - - - - - + - - - - - - - + - - - - - - - - - - - - - - - - - - + - + - - - - - - - - - - - - - - - + - - + diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/IJExpression.java b/jcodemodel/src/main/java/com/helger/jcodemodel/IJExpression.java index 512adf402..d41d4f41b 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/IJExpression.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/IJExpression.java @@ -52,7 +52,7 @@ * (by often taking other {@link IJExpression}s as parameters. For example, you can build "5+2" by * JExpr.lit(5).add(JExpr.lit(2)) */ -public interface IJExpression extends IJGenerable +public interface IJExpression extends IVariableInitializer { /** * @return -[this]" from "[this]. diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/IJFormatter.java b/jcodemodel/src/main/java/com/helger/jcodemodel/IJFormatter.java index 6a1614fbc..033dab1b6 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/IJFormatter.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/IJFormatter.java @@ -45,6 +45,9 @@ import org.jspecify.annotations.NonNull; +import com.helger.jcodemodel.writer.FormatterSettings; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping; + /** * Base interface for JFormatter. * @@ -72,7 +75,13 @@ public interface IJFormatter extends Closeable * @return this for chaining */ @NonNull - IJFormatter indent (); + default IJFormatter indent () + { + return indent (1); + } + + @NonNull + IJFormatter indent (int nb); /** * Decrement the indentation level. @@ -80,7 +89,13 @@ public interface IJFormatter extends Closeable * @return this for chaining */ @NonNull - IJFormatter outdent (); + default IJFormatter outdent () + { + return outdent (1); + } + + @NonNull + IJFormatter outdent (int nb); /** * Print a new line into the stream @@ -89,11 +104,16 @@ public interface IJFormatter extends Closeable */ @NonNull IJFormatter newline (); - + /** * @return the internal String used for new lines. */ - String getNewLine(); + String getNewLine (); + + /** + * @return the size of the line written, so far. + */ + int currentLineSize (); /** * Print a char into the stream @@ -121,6 +141,11 @@ default IJFormatter printCloseTypeArgs () @NonNull IJFormatter print (@NonNull String sStr); + default IJFormatter println (@NonNull String sStr) + { + return print (sStr).print (getNewLine ()); + } + /** * Print a type name. *

@@ -153,6 +178,13 @@ default IJFormatter type (@NonNull final AbstractJType aType) @NonNull IJFormatter var (@NonNull JVar aVar); + default IJFormatter vars (@NonNull final Collection aList) + { + return vars (aList, null); + } + + IJFormatter vars (@NonNull final Collection aList, ListWrapping wrapping); + /** * Print an identifier * @@ -182,7 +214,13 @@ default IJFormatter type (@NonNull final AbstractJType aType) * @return this for chaining */ @NonNull - IJFormatter generable (@NonNull final Collection aList); + default IJFormatter generable (@NonNull final Collection aList) + { + return generable (aList, ",", null); + } + + @NonNull + IJFormatter generable (@NonNull final Collection aList, String separator, ListWrapping wrapping); /** * Cause the {@link IJStatement} to generate source for itself @@ -203,4 +241,42 @@ default IJFormatter type (@NonNull final AbstractJType aType) */ @NonNull IJFormatter declaration (@NonNull IJDeclaration aObj); + + FormatterSettings settings (); + + public interface IContextCloser extends AutoCloseable + { + @Override + void close (); + + IContextCloser persistOnClose (boolean b); + + default IContextCloser persistOnClose () + { + return persistOnClose (true); + } + + /// shortcut to set the persist then close. Since the close is idempotent, this + /// call may have no result. + default void commit () + { + persistOnClose ().close (); + } + + /// shortcut to unset the persist then close. Since the close is idempotent, + /// this call may have no result. + default void rollback () + { + persistOnClose (false).close (); + } + + /// @return true after #close has been called at least once. + boolean isClosed (); + + /// get the actual buffer's value + String value (); + } + + /// create a new buffer to write data into. + IContextCloser addContextLayer (); } diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/IVariableInitializer.java b/jcodemodel/src/main/java/com/helger/jcodemodel/IVariableInitializer.java new file mode 100644 index 000000000..964681965 --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/IVariableInitializer.java @@ -0,0 +1,6 @@ +package com.helger.jcodemodel; + +/// marker for classes that are allowed to be used as variable initializers. +public interface IVariableInitializer extends IJGenerable { + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/JBlock.java b/jcodemodel/src/main/java/com/helger/jcodemodel/JBlock.java index faabcbbb8..66d9dbb75 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/JBlock.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/JBlock.java @@ -49,6 +49,7 @@ import com.helger.annotation.Nonnegative; import com.helger.base.enforce.ValueEnforcer; +import com.helger.jcodemodel.vars.JBlockVar; /** * A block of Java code, which may contain statements and local declarations. @@ -219,8 +220,8 @@ public int pos () @Nonnegative public int pos (@Nonnegative final int nNewPos) { - ValueEnforcer.isTrue (nNewPos >= 0 && nNewPos <= m_aContentList.size (), - () -> "Illegal position provided: " + nNewPos); + ValueEnforcer.isTrue ( (nNewPos >= 0) && (nNewPos <= m_aContentList.size ()), + () -> "Illegal position provided: " + nNewPos); final int nOldPos = m_nPos; m_nPos = nNewPos; @@ -255,7 +256,7 @@ public int size () * @return Newly generated {@link JVar} */ @NonNull - public JVar decl (final AbstractJType aType, @NonNull final String sName) + public JBlockVar decl (final AbstractJType aType, @NonNull final String sName) { return decl (JMod.NONE, aType, sName, null); } @@ -273,7 +274,7 @@ public JVar decl (final AbstractJType aType, @NonNull final String sName) * @return Newly generated {@link JVar} */ @NonNull - public JVar decl (final int nMods, @NonNull final AbstractJType aType, @NonNull final String sName) + public JBlockVar decl (final int nMods, @NonNull final AbstractJType aType, @NonNull final String sName) { return decl (nMods, aType, sName, null); } @@ -291,7 +292,10 @@ public JVar decl (final int nMods, @NonNull final AbstractJType aType, @NonNull * @return Newly generated {@link JVar} */ @NonNull - public JVar decl (@NonNull final AbstractJType aType, @NonNull final String sName, @Nullable final IJExpression aInit) + public JBlockVar decl ( + @NonNull final AbstractJType aType, + @NonNull final String sName, + @Nullable final IVariableInitializer aInit) { return decl (JMod.NONE, aType, sName, aInit); } @@ -311,12 +315,13 @@ public JVar decl (@NonNull final AbstractJType aType, @NonNull final String sNam * @return Newly generated {@link JVar} */ @NonNull - public JVar decl (final int nMods, - final AbstractJType aType, - @NonNull final String sName, - @Nullable final IJExpression aInit) + public JBlockVar decl ( + final int nMods, + final AbstractJType aType, + @NonNull final String sName, + @Nullable final IVariableInitializer aInit) { - final JVar v = new JVar (JMods.forVar (nMods), aType, sName, aInit); + final JBlockVar v = new JBlockVar (JMods.forVar (nMods), aType, sName, aInit); internalInsert (v); return v; } @@ -562,7 +567,9 @@ public JBlock addSingleLineComment () public JBlock addSingleLineComment (@Nullable final String sComment) { if (sComment != null) + { internalInsert (new JSingleLineCommentStatement (sComment)); + } return this; } @@ -608,9 +615,10 @@ public JConditional _if (@NonNull final IJExpression aTestExpr, @NonNull final I * @return Newly generated {@link JConditional} statement */ @NonNull - public JConditional _if (@NonNull final IJExpression aTestExpr, - @NonNull final IJStatement aThen, - @NonNull final IJStatement aElse) + public JConditional _if ( + @NonNull final IJExpression aTestExpr, + @NonNull final IJStatement aThen, + @NonNull final IJStatement aElse) { final JConditional aCond = new JConditional (aTestExpr); aCond._then ().add (aThen); @@ -745,8 +753,12 @@ public JThrow _throw (@NonNull final AbstractJClass aThrowClass, @NonNull final { final JInvocation aCtor = JExpr._new (aThrowClass); if (aParams != null) + { for (final IJExpression aParam : aParams) + { aCtor.arg (aParam); + } + } return _throw (aCtor); } @@ -883,9 +895,10 @@ public JBlock block (final boolean bBracesRequired, final boolean bIndentRequire * @return Newly generated enhanced For statement per j2se 1.5 specification */ @NonNull - public JForEach forEach (@NonNull final AbstractJType aVarType, - @NonNull final String sName, - @NonNull final IJExpression aCollection) + public JForEach forEach ( + @NonNull final AbstractJType aVarType, + @NonNull final String sName, + @NonNull final IJExpression aCollection) { return forEach (0, aVarType, sName, aCollection); } @@ -904,10 +917,11 @@ public JForEach forEach (@NonNull final AbstractJType aVarType, * @return Newly generated enhanced For statement per j2se 1.5 specification */ @NonNull - public JForEach forEach (final int nMods, - @NonNull final AbstractJType aVarType, - @NonNull final String sName, - @NonNull final IJExpression aCollection) + public JForEach forEach ( + final int nMods, + @NonNull final AbstractJType aVarType, + @NonNull final String sName, + @NonNull final IJExpression aCollection) { return internalInsert (new JForEach (JMods.forVar (nMods), aVarType, sName, aCollection)); } @@ -945,6 +959,7 @@ public IJStatement directStatement (@NonNull final String sSource) return aStatement; } + @Override public void generate (@NonNull final IJFormatter f) { if (m_bVirtualBlock) @@ -960,36 +975,48 @@ public void generate (@NonNull final IJFormatter f) f.newline (); } if (m_bIndentRequired) + { f.indent (); + } generateBody (f); if (m_bIndentRequired) + { f.outdent (); + } if (m_bBracesRequired) + { f.print ('}'); } } + } protected void generateBody (@NonNull final IJFormatter f) { for (final IJObject aContentElement : m_aContentList) { - if (aContentElement instanceof IJDeclaration) - f.declaration ((IJDeclaration) aContentElement); + if (aContentElement instanceof IJDeclaration ijd) + { + f.declaration (ijd); + } + else if (aContentElement instanceof IJStatement ijs) + { + f.statement (ijs); + } else - if (aContentElement instanceof IJStatement) - f.statement ((IJStatement) aContentElement); - else - { - // For lambda expressions in JLambdaBlock - f.generable ((IJGenerable) aContentElement); - } + { + // For lambda expressions in JLambdaBlock + f.generable ((IJGenerable) aContentElement); + } } } + @Override public void state (@NonNull final IJFormatter f) { f.generable (this); if (m_bBracesRequired) + { f.newline (); } } +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/JCatchBlock.java b/jcodemodel/src/main/java/com/helger/jcodemodel/JCatchBlock.java index 15d03021b..5ba167950 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/JCatchBlock.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/JCatchBlock.java @@ -43,37 +43,38 @@ import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; +import com.helger.jcodemodel.vars.JCatchFormalParameter; + /** * Catch block for a try/catch/finally statement */ public class JCatchBlock implements IJGenerable { - private final AbstractJClass m_aException; - private JVar m_aVar; + @NonNull + private final JCatchFormalParameter m_aVar; private final JBlock m_aBody = new JBlock (); public JCatchBlock (@NonNull final AbstractJClass aException) { - m_aException = aException; + m_aVar = new JCatchFormalParameter (true, aException, "ex"); } @NonNull public AbstractJClass exception () { - return m_aException; + return m_aVar.type (); } + /// shortcut to change the name of the variable and return it. @NonNull - public JVar param (final String sName) + public JCatchFormalParameter param (final String sName) { - if (m_aVar != null) - throw new IllegalStateException ("A variable is already present!"); - m_aVar = new JVar (JMods.forVar (JMod.FINAL), m_aException, sName, null); + m_aVar.name (sName); return m_aVar; } @Nullable - public JVar param () + public JCatchFormalParameter param () { return m_aVar; } @@ -84,10 +85,12 @@ public JBlock body () return m_aBody; } + @Override public void generate (@NonNull final IJFormatter f) { - if (m_aVar == null) - m_aVar = new JVar (JMods.forVar (JMod.FINAL), m_aException, "ex", null); - f.print ("catch (").var (m_aVar).print (')').generable (m_aBody); + f.print ("catch (") + .var (m_aVar) + .print (')') + .generable (m_aBody); } } diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/JDefinedClass.java b/jcodemodel/src/main/java/com/helger/jcodemodel/JDefinedClass.java index 44f83cd19..406fb9974 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/JDefinedClass.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/JDefinedClass.java @@ -597,7 +597,7 @@ public JFieldVar field (final int nMods, final Class aType, final String sNa public JFieldVar field (final int nMods, @NonNull final AbstractJType aType, @NonNull final String sName, - @Nullable final IJExpression aInit) + @Nullable final IVariableInitializer aInit) { ValueEnforcer.isFalse (m_aFields.containsKey (sName), () -> "trying to create the same field twice: " + sName); diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/JExpr.java b/jcodemodel/src/main/java/com/helger/jcodemodel/JExpr.java index 55cb513a8..4636441b3 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/JExpr.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/JExpr.java @@ -40,12 +40,17 @@ */ package com.helger.jcodemodel; +import java.nio.CharBuffer; +import java.util.function.Function; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; import java.util.stream.Stream; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; import com.helger.annotation.Nonnegative; +import com.helger.jcodemodel.expression.JArrayInit; /** * Factory methods that generate various {@link IJExpression}s. @@ -210,9 +215,10 @@ public static JInvocation invoke (@Nullable final IJExpression aLhs, @NonNull fi } @NonNull - public static JInvocation invoke (@Nullable final JCodeModel aOwner, - @Nullable final IJExpression aLhs, - @NonNull final String sMethod) + public static JInvocation invoke ( + @Nullable final JCodeModel aOwner, + @Nullable final IJExpression aLhs, + @NonNull final String sMethod) { return new JInvocation (aOwner, aLhs, sMethod); } @@ -324,7 +330,8 @@ public static JFieldRef refthis (@Nullable final IJExpression aLhs, @NonNull fin @NonNull public static IJExpression dotClass (@NonNull final AbstractJType aClass) { - return (@NonNull final IJFormatter f) -> { + return (@NonNull final IJFormatter f) -> + { final AbstractJType c = aClass instanceof final JNarrowedClass j ? j.basis () : aClass; f.generable (c).print (".class"); }; @@ -379,6 +386,50 @@ public static JArray newArray (@NonNull final AbstractJType aType, @Nonnegative return newArray (aType, lit (nSize)); } + /** + * Generates static array init for variables + * @return a new array static init + */ + public static JArrayInit arrayInit (IVariableInitializer... initializers) + { + return new JArrayInit (initializers); + } + + static JArrayInit arrayInit (Stream stream, Function converter) + { + return new JArrayInit (stream.map (converter).toArray (IVariableInitializer[]::new)); + } + + public static JArrayInit arrayInit (int start, int... rest) + { + return arrayInit ( + IntStream.concat ( + IntStream.of (start), + rest == null ? IntStream.empty () : IntStream.of (rest)) + .boxed (), + JExpr::lit); + } + + public static JArrayInit arrayInit (char start, char... rest) + { + return arrayInit ( + IntStream.concat ( + IntStream.of (start), + rest == null ? IntStream.empty () : CharBuffer.wrap (rest).chars ()) + .boxed (), + i -> lit ((char) (int) i)); + } + + public static JArrayInit arrayInit (double start, double... rest) + { + return arrayInit ( + DoubleStream.concat ( + DoubleStream.of (start), + rest == null ? DoubleStream.empty () : DoubleStream.of (rest)) + .boxed (), + (Function ) JExpr::lit); + } + /** * @return a reference to "this", an implicit reference to the current object. */ @@ -456,7 +507,7 @@ public static String quotify (final char cQuote, @NonNull final String sStr) final int j = CHAR_ESCAPE.indexOf (c); if (j >= 0) { - if ((cQuote == '"' && c == '\'') || (cQuote == '\'' && c == '"')) + if ( ( (cQuote == '"') && (c == '\'')) || ( (cQuote == '\'') && (c == '"'))) { sb.append (c); } @@ -466,29 +517,28 @@ public static String quotify (final char cQuote, @NonNull final String sStr) sb.append (CHAR_MACRO.charAt (j)); } } - else + else // technically Unicode escape shouldn't be done here, + // for it's a lexical level handling. + // + // However, various tools are so broken around this area, + // so just to be on the safe side, it's better to do + // the escaping here (regardless of the actual file encoding) + // + // see bug + if ( (c < 0x20) || (c > 0x7E)) { - // technically Unicode escape shouldn't be done here, - // for it's a lexical level handling. - // - // However, various tools are so broken around this area, - // so just to be on the safe side, it's better to do - // the escaping here (regardless of the actual file encoding) - // - // see bug - if (c < 0x20 || c > 0x7E) - { - // not printable. use Unicode escape - sb.append ("\\u"); - final String hex = Integer.toHexString (c & 0xFFFF); - for (int k = hex.length (); k < 4; k++) - sb.append ('0'); - sb.append (hex); - } - else + // not printable. use Unicode escape + sb.append ("\\u"); + final String hex = Integer.toHexString (c & 0xFFFF); + for (int k = hex.length (); k < 4; k++) { - sb.append (c); + sb.append ('0'); } + sb.append (hex); + } + else + { + sb.append (c); } } sb.append (cQuote); @@ -506,13 +556,15 @@ public static JStringLiteral lit (@NonNull final String sStr) { return new JStringLiteral (sStr); } - + @NonNull - public static JTextBlock textBlock (@NonNull final String ... lines) + public static JTextBlock textBlock (@NonNull final String... lines) { - JTextBlock ret = new JTextBlock(); - if(lines!=null && lines.length!=0) - Stream.of(lines).forEach(ret::add); + JTextBlock ret = new JTextBlock (); + if ( (lines != null) && (lines.length != 0)) + { + Stream.of (lines).forEach (ret::add); + } return ret; } @@ -547,9 +599,10 @@ public static IJExpression direct (@NonNull final String sSourceCode) * @return The created aExpr */ @NonNull - public static JOpTernary cond (@NonNull final IJExpression aCond, - @NonNull final IJExpression aIfTrue, - @NonNull final IJExpression aIfFalse) + public static JOpTernary cond ( + @NonNull final IJExpression aCond, + @NonNull final IJExpression aIfTrue, + @NonNull final IJExpression aIfFalse) { return JOp.cond (aCond, aIfTrue, aIfFalse); } diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/JFieldVar.java b/jcodemodel/src/main/java/com/helger/jcodemodel/JFieldVar.java index 4cab827c2..bd1d0cb9c 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/JFieldVar.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/JFieldVar.java @@ -47,11 +47,13 @@ import com.helger.base.enforce.ValueEnforcer; import com.helger.base.equals.EqualsHelper; +import com.helger.jcodemodel.vars.JBlockVar; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping; /** * A field that can have a {@link JDocComment} associated with it */ -public class JFieldVar extends JVar implements IJDocCommentable +public class JFieldVar extends JBlockVar implements IJDocCommentable { private final JDefinedClass m_aOwnerClass; @@ -78,7 +80,7 @@ protected JFieldVar (@NonNull final JDefinedClass aOwnerClass, @NonNull final JMods aMods, @NonNull final AbstractJType aType, @NonNull final String sName, - @Nullable final IJExpression aInit) + @Nullable final IVariableInitializer aInit) { super(aMods, ValueEnforcer.notNull(aType, "type"), sName, aInit); m_aOwnerClass = ValueEnforcer.notNull (aOwnerClass, "OwnerClass"); @@ -104,11 +106,13 @@ public void name (@NonNull final String sNewName) m_aOwnerClass.internalRenameField (sOldName, sNewName, this); } + @Override @NonNull public JDocComment javadoc () { - if (m_aJavaDoc == null) + if (m_aJavaDoc == null) { m_aJavaDoc = new JDocComment (m_aOwnerClass.owner ()); + } return m_aJavaDoc; } @@ -126,25 +130,21 @@ public JFieldRef fieldRef () public void declare (@NonNull final IJFormatter f) { // Declaration - if (m_aJavaDoc != null) + if (m_aJavaDoc != null) { f.generable (m_aJavaDoc); - super.declare (f); - } - - @Override - public void generate (@NonNull final IJFormatter f) - { - // Usage - super.generate (f); + } + super.declare(f); } @Override public boolean equals (final Object o) { - if (o == this) + if (o == this) { return true; - if (!super.equals (o)) + } + if (!super.equals (o)) { return false; + } final JFieldVar rhs = (JFieldVar) o; return EqualsHelper.equals (m_aOwnerClass, rhs.m_aOwnerClass); } @@ -154,4 +154,9 @@ public int hashCode () { return getHashCode (super.hashCode (), new Object [] { m_aOwnerClass }); } + + @Override + protected ListWrapping extractWrappingOptions(@NonNull IJFormatter f) { + return f.settings().wrap.variables.field; + } } diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/JForEach.java b/jcodemodel/src/main/java/com/helger/jcodemodel/JForEach.java index 6961f4209..c598e2633 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/JForEach.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/JForEach.java @@ -41,8 +41,10 @@ package com.helger.jcodemodel; import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; import com.helger.base.enforce.ValueEnforcer; +import com.helger.jcodemodel.vars.JForEachVar; /** * ForEach Statement This will generate the code for statement based on the new @@ -52,28 +54,18 @@ */ public class JForEach implements IJStatement { - private final JMods m_aMods; - private final AbstractJType m_aType; - private final String m_sVarName; private JBlock m_aBody; // lazily created - private final IJExpression m_aCollection; - private final JVar m_aLoopVar; + private final JForEachVar m_aLoopVar; public JForEach (@NonNull final JMods aMods, - @NonNull final AbstractJType aVarType, + @Nullable final AbstractJType aVarType, @NonNull final String sVarName, @NonNull final IJExpression aCollection) { ValueEnforcer.notNull (aMods, "Mods"); - ValueEnforcer.notNull (aVarType, "VarType"); ValueEnforcer.notNull (sVarName, "VarName"); ValueEnforcer.notNull (aCollection, "Collection"); - - m_aMods = aMods; - m_aType = aVarType; - m_sVarName = sVarName; - m_aCollection = aCollection; - m_aLoopVar = new JVar (JMods.forVar (JMod.FINAL), m_aType, m_sVarName, aCollection); + m_aLoopVar = new JForEachVar (aMods.isFinal (), aVarType, sVarName, aCollection); } /** @@ -83,13 +75,13 @@ public JForEach (@NonNull final JMods aMods, @NonNull public JMods mods () { - return m_aMods; + return m_aLoopVar.mods(); } @NonNull public AbstractJType type () { - return m_aType; + return m_aLoopVar.type(); } /** @@ -104,26 +96,31 @@ public JVar var () @NonNull public IJExpression collection () { - return m_aCollection; + return m_aLoopVar.collection(); } @NonNull public JBlock body () { - if (m_aBody == null) + if (m_aBody == null) { m_aBody = new JBlock (); + } return m_aBody; } + @Override public void state (@NonNull final IJFormatter f) { f.print ("for ("); - f.generable (m_aMods).generable (m_aType).id (m_sVarName).print (": ").generable (m_aCollection); + f.var(m_aLoopVar); + // f.generable (m_aMods).generable (m_aType).id (m_sVarName).print (": + // ").generable (m_aCollection); f.print (')'); - if (m_aBody != null) + if (m_aBody != null) { f.generable (m_aBody); - else + } else { f.print (';'); + } f.newline (); } } diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/JForLoop.java b/jcodemodel/src/main/java/com/helger/jcodemodel/JForLoop.java index 9d16ff115..6a9c9709c 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/JForLoop.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/JForLoop.java @@ -6,11 +6,11 @@ * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific + * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each @@ -30,10 +30,10 @@ * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a + * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code + * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. @@ -48,49 +48,75 @@ import org.jspecify.annotations.Nullable; import com.helger.base.enforce.ValueEnforcer; +import com.helger.jcodemodel.vars.JBlockVar; /** * For statement */ -public class JForLoop implements IJStatement -{ - private final List m_aInitExprs = new ArrayList <> (); +public class JForLoop implements IJStatement { + + // either a init var, or expressions + private JBlockVar m_aInitVar; + private final List m_aInitExprs = new ArrayList<>(); private IJExpression m_aTestExpr; - private final List m_aUpdateExprs = new ArrayList <> (); + private final List m_aUpdateExprs = new ArrayList<>(); private JBlock m_aBody; - public JForLoop () - {} + public JForLoop() { + } + + public JBlockVar getInitVar() { + return m_aInitVar; + } + + /// thow an exception if can't create a new var + protected void checkInitVar() { + if (m_aInitVar != null) + throw new IllegalStateException ("a for loop can only have one type variable, this already has one"); + if (!m_aInitExprs.isEmpty()) + throw new IllegalStateException ( + "a for loop must have either variable declaration or expressions, this already has expressions"); + } + + /// @return true if we can init using expressions + protected void checkInitExpr() { + if (m_aInitVar != null) + throw new IllegalStateException ( + "a for loop must have either variable declaration or expressions, this already has variable"); + } @NonNull - public JVar init (final int nMods, - @NonNull final AbstractJType aType, - @NonNull final String sVarName, - @Nullable final IJExpression aInitExpr) - { - final JVar aVar = new JVar (JMods.forVar (nMods), aType, sVarName, aInitExpr); - m_aInitExprs.add (aVar); + public JBlockVar init(final int nMods, + @NonNull final AbstractJType aType, + @NonNull final String sVarName, + @Nullable final IJExpression aInitExpr) { + checkInitVar(); + final JBlockVar aVar = new JBlockVar(JMods.forVar(nMods), aType, sVarName, aInitExpr); + m_aInitVar = aVar; return aVar; } @NonNull - public JVar init (@NonNull final AbstractJType aType, @NonNull final String sVarName, @Nullable final IJExpression aInitExpr) - { - return init (JMod.NONE, aType, sVarName, aInitExpr); + public JBlockVar + init(@NonNull final AbstractJType aType, @NonNull final String sVarName, @Nullable final IJExpression aInitExpr) { + return init(JMod.NONE, aType, sVarName, aInitExpr); } - public void init (@NonNull final JVar aVar, @NonNull final IJExpression aRhs) - { - final JAssignment aAssignment = JExpr.assign (aVar, aRhs); - m_aInitExprs.add (aAssignment); + public JForLoop init(@NonNull final JVar aVar, @NonNull final IJExpression aRhs) { + return init(JExpr.assign(aVar, aRhs)); + } + + public JForLoop init(IJExpression ije) { + checkInitExpr(); + m_aInitExprs.add(ije); + return this; } /** * @return List of {@link IJExpression} or {@link JVar} */ @NonNull - public List initsMutable () - { + public List initsMutable() { return m_aInitExprs; } @@ -98,66 +124,93 @@ public List initsMutable () * @return List of {@link IJExpression} or {@link JVar} */ @NonNull - public List inits () - { - return Collections.unmodifiableList (initsMutable ()); + public List inits() { + return Collections.unmodifiableList(initsMutable()); } - public void test (@Nullable final IJExpression aTestExpr) - { + public void test(@Nullable final IJExpression aTestExpr) { m_aTestExpr = aTestExpr; } @Nullable - public IJExpression test () - { + public IJExpression test() { return m_aTestExpr; } - public void update (@NonNull final IJExpression aUpdate) - { - ValueEnforcer.notNull (aUpdate, "Update"); - m_aUpdateExprs.add (aUpdate); + public void update(@NonNull final IJExpression aUpdate) { + ValueEnforcer.notNull(aUpdate, "Update"); + m_aUpdateExprs.add(aUpdate); } @NonNull - public List updatesMutable () - { + public List updatesMutable() { return m_aUpdateExprs; } @NonNull - public List updates () - { - return Collections.unmodifiableList (updatesMutable ()); + public List updates() { + return Collections.unmodifiableList(updatesMutable()); } @NonNull - public JBlock body () - { - if (m_aBody == null) - m_aBody = new JBlock (); + public JBlock body() { + if (m_aBody == null) { + m_aBody = new JBlock(); + } return m_aBody; } - public void state (@NonNull final IJFormatter f) - { - f.print ("for ("); - boolean bFirst = true; - for (final Object o : m_aInitExprs) + @Override + public void state(@NonNull final IJFormatter f) { + f.print("for ("); + stateInit(f); + f.print(';'); + if (m_aTestExpr != null) { + f.generable(m_aTestExpr); + } + f.print(';'); + if (m_aUpdateExprs != null) { + f.generable(m_aUpdateExprs); + } + f.print(')'); + if (m_aBody != null) { + f.generable(m_aBody).newline(); + } else { + f.print(';').newline(); + } + } + + protected void stateInit(@NonNull final IJFormatter f) { + if (m_aInitVar != null) { - if (!bFirst) - f.print (','); - if (o instanceof JVar) - f.var ((JVar) o); - else - f.generable ((IJExpression) o); - bFirst = false; + // init a variable + if (f.settings().wrap.disabled) { + boolean bFirst = true; + for (final JVar o : m_aInitVar.streamVars ().toList ()) + { + if (!bFirst) { + f.print(','); + } + f.var(o); + bFirst = false; + } + } else { + f.vars (m_aInitVar.streamVars ().toList (), f.settings ().wrap.forLoop.init); + } + } else + // init a list of expressions + if (f.settings().wrap.disabled) { + boolean bFirst = true; + for (final IJExpression o : m_aInitExprs) { + if (!bFirst) { + f.print(','); + } + f.generable(o); + bFirst = false; + } + } else { + f.generable(m_aInitExprs, ",", f.settings().wrap.forLoop.init); } - f.print (';').generable (m_aTestExpr).print (';').generable (m_aUpdateExprs).print (')'); - if (m_aBody != null) - f.generable (m_aBody).newline (); - else - f.print (';').newline (); + } } diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/JMethod.java b/jcodemodel/src/main/java/com/helger/jcodemodel/JMethod.java index c2064fd07..2fb7c24c6 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/JMethod.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/JMethod.java @@ -47,6 +47,7 @@ import java.util.List; import java.util.Set; import java.util.TreeSet; +import java.util.stream.Stream; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; @@ -54,6 +55,9 @@ import com.helger.annotation.Nonnegative; import com.helger.base.enforce.ValueEnforcer; import com.helger.jcodemodel.util.ClassNameComparator; +import com.helger.jcodemodel.vars.JArgVar; +import com.helger.jcodemodel.vars.JVarArgVar; +import com.helger.jcodemodel.writer.settings.Wrap.WordWrapping.EWordWrapStrategy; /** * Java method. @@ -102,7 +106,7 @@ public class JMethod extends AbstractJGenerifiableImpl implements IJAnnotatable, * Variable parameter for this method's varargs declaration introduced in J2SE * 1.5 */ - private JVar m_aVarParam; + private JVarArgVar m_aVarParam; /** * Annotations on this variable. Lazily created. @@ -234,9 +238,9 @@ public JVar paramAtIndex (@Nonnegative final int nIndex) throws IndexOutOfBounds * @return New parameter variable of type {@link JVar} */ @NonNull - public JVar param (final int nMods, @NonNull final AbstractJType aType, @NonNull final String sName) + public JArgVar param(final int nMods, @NonNull final AbstractJType aType, @NonNull final String sName) { - final JVar aVar = new JVar (JMods.forVar (nMods), ValueEnforcer.notNull(aType, "type"), sName, null); + final JArgVar aVar = new JArgVar((nMods | JMod.FINAL) > 0, ValueEnforcer.notNull(aType, "type"), sName); m_aParams.add (aVar); return aVar; } @@ -273,7 +277,7 @@ public JVar param (@NonNull final Class aType, @NonNull final String sName) * once in the method signature. */ @NonNull - public JVar varParam (@NonNull final Class aType, @NonNull final String sName) + public JVarArgVar varParam(@NonNull final Class aType, @NonNull final String sName) { return varParam (m_aOwningClass.owner ()._ref (aType), sName); } @@ -292,7 +296,7 @@ public JVar varParam (@NonNull final Class aType, @NonNull final String sNam * once in the method signature. */ @NonNull - public JVar varParam (@NonNull final AbstractJType aType, @NonNull final String sName) + public JVarArgVar varParam(@NonNull final AbstractJType aType, @NonNull final String sName) { return varParam (JMod.NONE, aType, sName); } @@ -314,7 +318,7 @@ public JVar varParam (@NonNull final AbstractJType aType, @NonNull final String * once in the method signature. */ @NonNull - public JVar varParam (final int nMods, @NonNull final Class aType, @NonNull final String sName) + public JVarArgVar varParam(final int nMods, @NonNull final Class aType, @NonNull final String sName) { return varParam (nMods, m_aOwningClass.owner ()._ref (aType), sName); } @@ -336,17 +340,20 @@ public JVar varParam (final int nMods, @NonNull final Class aType, @NonNull * once in the method signature. */ @NonNull - public JVar varParam (final int nMods, @NonNull final AbstractJType aType, @NonNull final String sName) + public JVarArgVar varParam(final int nMods, @NonNull final AbstractJType aType, @NonNull final String sName) { ValueEnforcer.isFalse (hasVarArgs (), - "Cannot have two varargs in a method,\n" + "Check if varParam method of JMethod is" + " invoked more than once"); + """ + Cannot have two varargs in a method, + Check if varParam method of JMethod is\ + invoked more than once"""); - m_aVarParam = new JVar (JMods.forVar (nMods), aType.array (), sName, null); + m_aVarParam = new JVarArgVar((nMods | JMod.FINAL) > 0, aType.array(), sName); return m_aVarParam; } @Nullable - public JVar varParam () + public JVarArgVar varParam() { return m_aVarParam; } @@ -378,11 +385,13 @@ public AbstractJType listVarParamType () * The annotation class to annotate the field with * @return The created object. Never null. */ + @Override @NonNull public JAnnotationUse annotate (@NonNull final AbstractJClass aClazz) { - if (m_aAnnotations == null) + if (m_aAnnotations == null) { m_aAnnotations = new ArrayList <> (); + } final JAnnotationUse a = new JAnnotationUse (aClazz); m_aAnnotations.add (a); return a; @@ -395,6 +404,7 @@ public JAnnotationUse annotate (@NonNull final AbstractJClass aClazz) * The annotation class to annotate the field with * @return The created object. Never null. */ + @Override @NonNull public JAnnotationUse annotate (@NonNull final Class aClazz) { @@ -404,11 +414,13 @@ public JAnnotationUse annotate (@NonNull final Class aCla @NonNull public List annotationsMutable () { - if (m_aAnnotations == null) + if (m_aAnnotations == null) { return Collections.emptyList (); + } return m_aAnnotations; } + @Override @NonNull public Collection annotations () { @@ -462,8 +474,9 @@ public void type (@Nullable final AbstractJType aReturnType) public AbstractJType [] listParamTypes () { final AbstractJType [] r = new AbstractJType [m_aParams.size ()]; - for (int i = 0; i < r.length; i++) + for (int i = 0; i < r.length; i++) { r[i] = m_aParams.get (i).type (); + } return r; } @@ -488,12 +501,15 @@ public void type (@Nullable final AbstractJType aReturnType) public boolean hasSignature (@NonNull final AbstractJType [] argTypes) { final JVar [] aParams = listParams (); - if (aParams.length != argTypes.length) + if (aParams.length != argTypes.length) { return false; + } - for (int i = 0; i < aParams.length; i++) - if (!aParams[i].type ().equals (argTypes[i])) + for (int i = 0; i < aParams.length; i++) { + if (!aParams[i].type ().equals (argTypes[i])) { return false; + } + } return true; } @@ -506,8 +522,9 @@ public boolean hasSignature (@NonNull final AbstractJType [] argTypes) @NonNull public JBlock body () { - if (m_aBody == null) + if (m_aBody == null) { m_aBody = new JBlock (); + } return m_aBody; } @@ -522,11 +539,13 @@ public void declareDefaultValue (@Nullable final IJExpression aDefaultValue) m_aDefaultValue = aDefaultValue; } + @Override @NonNull public JDocComment javadoc () { - if (m_aJDoc == null) + if (m_aJDoc == null) { m_aJDoc = new JDocComment (owner ()); + } return m_aJDoc; } @@ -542,53 +561,54 @@ public boolean hasJavadoc () @Override public void declare (@NonNull final IJFormatter f) { - if (m_aJDoc != null) + if (m_aJDoc != null) { f.generable (m_aJDoc); + } - if (m_aAnnotations != null) - for (final JAnnotationUse a : m_aAnnotations) + if (m_aAnnotations != null) { + for (final JAnnotationUse a : m_aAnnotations) { f.generable (a).newline (); + } + } f.generable (m_aMods); // declare the generics parameters super.declare (f); - if (!isConstructor ()) + if (!isConstructor ()) { f.generable (m_aReturnType); - f.id (m_sName).print ('(').indent (); - // when parameters are printed in new lines, we want them to be indented. - // there's a good chance no newlines happen, too, but just in case it does. - - boolean bFirst = true; - // break only if more than 3 variables are present - final boolean bNewLineAfterParam = (m_aParams.size () + (hasVarArgs () ? 1 : 0)) > 3; - for (final JVar var : m_aParams) - { - if (bFirst) - bFirst = false; - else - { - f.print (','); - if (bNewLineAfterParam) - f.newline (); - } - f.var (var); } - if (hasVarArgs ()) - { - if (!bFirst) - { - f.print (','); - if (bNewLineAfterParam) - f.newline (); + + if (!f.settings().wrap.disabled) { + EWordWrapStrategy nameWrapStrat = f.settings().wrap.method.name.condition; + boolean wrapName = switch (nameWrapStrat) { + case ALWAYS -> true; + case NEVER -> false; + case REQUIRED -> f.currentLineSize() + m_sName.length() + 1 > f.settings().wrap.lineWidth; + }; + if (wrapName) { + int nbi = f.settings().wrap.method.name.indent; + f + .indent(nbi) + .newline() + .id(m_sName) + .outdent(nbi); + } else { + f.id(m_sName); } - for (final JAnnotationUse annotation : m_aVarParam.annotations ()) - f.generable (annotation).print (' '); - f.generable (m_aVarParam.mods ()).generable (m_aVarParam.type ().elementType ()).print ("... ").id (m_aVarParam.name ()); + } else { + f.id(m_sName); } - f.outdent ().print (')'); + f.print('('); + if (f.settings().wrap.disabled) { + appParamsWrapDisabled(f); + } else { + f.vars(Stream.concat(m_aParams.stream(), Stream.ofNullable(m_aVarParam)).toList(), + f.settings().wrap.method.params); + } + f.print(')'); if (!m_aThrows.isEmpty ()) { f.newline ().indent ().print ("throws").generable (m_aThrows).newline ().outdent (); @@ -602,11 +622,25 @@ public void declare (@NonNull final IJFormatter f) } if (m_aBody != null) { + if (!f.settings().wrap.disabled) { + EWordWrapStrategy bracketWrapStrat = f.settings().wrap.method.bracket.condition; + boolean wrapBracket = switch (bracketWrapStrat) { + case ALWAYS -> true; + case NEVER -> false; + case REQUIRED -> f.currentLineSize() + 2 > f.settings().wrap.lineWidth; + }; + if (wrapBracket) { + f + .indent(f.settings().wrap.method.bracket.indent) + .newline() + .outdent(f.settings().wrap.method.bracket.indent); + } + } f.statement (m_aBody); } else { - final boolean bIsDeclarationOnly = (m_aOwningClass.isInterface () && !m_aMods.isDefault ()) || + final boolean bIsDeclarationOnly = m_aOwningClass.isInterface () && !m_aMods.isDefault () || m_aOwningClass.isAnnotationTypeDeclaration () || m_aMods.isAbstract () || m_aMods.isNative (); @@ -617,12 +651,58 @@ public void declare (@NonNull final IJFormatter f) } else { + if (!f.settings().wrap.disabled) { + EWordWrapStrategy bracketWrapStrat = f.settings().wrap.method.bracket.condition; + boolean wrapBracket = switch (bracketWrapStrat) { + case ALWAYS -> true; + case NEVER -> false; + case REQUIRED -> f.currentLineSize() + 2 > f.settings().wrap.lineWidth; + }; + if (wrapBracket) { + f + .indent(f.settings().wrap.method.bracket.indent) + .newline() + .outdent(f.settings().wrap.method.bracket.indent); + } + } // Print an empty body for non-native, non-abstract methods f.statement (new JBlock ()); } } } + /// legacy params printing. + void appParamsWrapDisabled(@NonNull final IJFormatter f) { + f.indent(); + // when parameters are printed in new lines, we want them to be indented. + // there's a good chance no newlines happen, too, but just in case it does. + + boolean bFirst = true; + // break only if more than 3 variables are present + final boolean bNewLineAfterParam = m_aParams.size() + (hasVarArgs() ? 1 : 0) > 3; + for (final JVar var : m_aParams) { + if (bFirst) { + bFirst = false; + } else { + f.print(','); + if (bNewLineAfterParam) { + f.newline(); + } + } + f.var(var); + } + if (hasVarArgs()) { + if (!bFirst) { + f.print(','); + if (bNewLineAfterParam) { + f.newline(); + } + } + f.var(m_aVarParam); + } + f.outdent(); + } + /** * @return the current modifiers of this method. Always return non-null valid * object. @@ -643,6 +723,7 @@ public JDefinedClass owningClass () return m_aOwningClass; } + @Override @NonNull public JCodeModel owner () { diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/JTryBlock.java b/jcodemodel/src/main/java/com/helger/jcodemodel/JTryBlock.java index 0245eba9a..6d76f5f48 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/JTryBlock.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/JTryBlock.java @@ -140,6 +140,14 @@ public JCatchBlock _catch (@NonNull final AbstractJClass aException) return cb; } + /// create a catch block with given name + @NonNull + public JCatchBlock _catch(@NonNull final AbstractJClass aException, String name) { + final JCatchBlock cb = _catch(aException); + cb.param(name); + return cb; + } + /** * Get a list of all catch blocks. Since v3.2.3 the returned list is mutable. * Previously it was immutable. @@ -169,8 +177,9 @@ public boolean hasCatchBlock () @NonNull public JBlock _finally () { - if (m_aFinally == null) + if (m_aFinally == null) { m_aFinally = new JBlock (); + } return m_aFinally; } @@ -195,6 +204,7 @@ public boolean hasFinally () return m_aFinally != null; } + @Override public void state (@NonNull final IJFormatter f) { f.print ("try"); @@ -204,19 +214,22 @@ public void state (@NonNull final IJFormatter f) boolean bFirst = true; for (final JTryResource aResource : m_aResources) { - if (bFirst) + if (bFirst) { bFirst = false; - else + } else { f.print (';').newline (); + } f.generable (aResource); } f.print (')'); } f.generable (m_aBody); - for (final JCatchBlock cb : m_aCatches) + for (final JCatchBlock cb : m_aCatches) { f.generable (cb); - if (m_aFinally != null) + } + if (m_aFinally != null) { f.print ("finally").generable (m_aFinally); + } f.newline (); } } diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/JTryResource.java b/jcodemodel/src/main/java/com/helger/jcodemodel/JTryResource.java index df2bd3a46..c8594e81e 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/JTryResource.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/JTryResource.java @@ -42,6 +42,8 @@ import org.jspecify.annotations.NonNull; +import com.helger.jcodemodel.vars.JBlockVar; + /** * This class represents a single resources that is used in try-with-resources * statement. See {@link JTryBlock}. @@ -68,7 +70,7 @@ public JTryResource (final int nMods, @NonNull final String sName, @NonNull final IJExpression aInitExpr) { - m_aVar = new JVar (JMods.forVar (nMods), aType, sName, aInitExpr); + m_aVar = new JBlockVar(JMods.forVar(nMods), aType, sName, aInitExpr); m_bReuse = false; } @@ -84,11 +86,13 @@ public JVar var () return m_aVar; } + @Override public void generate (@NonNull final IJFormatter aFormatter) { - if (m_bReuse) + if (m_bReuse) { aFormatter.generable (m_aVar); - else + } else { aFormatter.var (m_aVar); + } } } diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/JVar.java b/jcodemodel/src/main/java/com/helger/jcodemodel/JVar.java index bb89b45bd..751391946 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/JVar.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/JVar.java @@ -55,7 +55,7 @@ /** * Variables and fields. */ -public class JVar implements IJAssignmentTarget, IJDeclaration, IJAnnotatable +public class JVar implements IJAssignmentTarget, IJAnnotatable { /** * Modifiers. @@ -75,7 +75,7 @@ public class JVar implements IJAssignmentTarget, IJDeclaration, IJAnnotatable /** * Initialization of the variable in its declaration */ - private IJExpression m_aInitExpr; + private IVariableInitializer m_aInitExpr; /** * Annotations on this variable. Lazily created. @@ -97,7 +97,7 @@ public class JVar implements IJAssignmentTarget, IJDeclaration, IJAnnotatable public JVar (@NonNull final JMods aMods, final AbstractJType aType, @NonNull final String sName, - @Nullable final IJExpression aInitExpr) + @Nullable final IVariableInitializer aInitExpr) { ValueEnforcer.isTrue (JJavaName.isJavaIdentifier (sName), () -> "Illegal variable name '" + sName + "'"); m_aMods = aMods; @@ -124,7 +124,7 @@ public JVar init (@Nullable final IJExpression aInitExpr) * @return The init expression. May be null. */ @Nullable - public IJExpression init () + public IVariableInitializer init() { return m_aInitExpr; } @@ -179,7 +179,6 @@ public JMods mods () */ public AbstractJType type (final AbstractJType aNewType) { - ValueEnforcer.notNull (aNewType, "NewType"); final AbstractJType aOldType = m_aType; m_aType = aNewType; return aOldType; @@ -277,10 +276,8 @@ public void bind (@NonNull final IJFormatter f) } } - @Override - public void declare (@NonNull final IJFormatter f) - { - f.var (this).print (';').newline (); + protected void declare(@NonNull final IJFormatter f) { + f.var(this).print(';').newline(); } @Override @@ -307,4 +304,9 @@ public int hashCode () { return new HashCodeGenerator (this).append (m_sName).getHashCode (); } + + /// the separator when several jvars are declared at one. + public String separator() { + return ";"; + } } diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/expression/JArrayInit.java b/jcodemodel/src/main/java/com/helger/jcodemodel/expression/JArrayInit.java new file mode 100644 index 000000000..ea83bd47b --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/expression/JArrayInit.java @@ -0,0 +1,35 @@ +package com.helger.jcodemodel.expression; + +import java.util.List; +import java.util.stream.Stream; + +import org.jspecify.annotations.NonNull; + +import com.helger.jcodemodel.IJFormatter; +import com.helger.jcodemodel.IVariableInitializer; +import com.helger.jcodemodel.JExpr; + +public class JArrayInit implements IVariableInitializer { + + @NonNull + private final List elements; + + public JArrayInit(IVariableInitializer... elements) { + this.elements = convertElements(elements); + } + + static List convertElements (IVariableInitializer[] elements) + { + if (elements == null) + return List.of (); + return Stream.of (elements).map (e -> e != null ? e : JExpr._null ()).toList (); + } + + @Override + public void generate(@NonNull IJFormatter f) { + f.print('{'); + f.generable (elements, ",", f.settings ().wrap.variables.array); + f.print('}'); + } + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/util/NullWriter.java b/jcodemodel/src/main/java/com/helger/jcodemodel/util/NullWriter.java index f308f1faf..8ed583473 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/util/NullWriter.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/util/NullWriter.java @@ -64,7 +64,7 @@ private NullWriter () {} @Override - public void write (final char [] cbuf, final int off, final int len) throws IOException + public void write (final char[] cbuf, final int off, final int len) throws IOException {} @Override diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JArgVar.java b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JArgVar.java new file mode 100644 index 000000000..df4fd665f --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JArgVar.java @@ -0,0 +1,46 @@ +package com.helger.jcodemodel.vars; + +import org.jspecify.annotations.NonNull; + +import com.helger.jcodemodel.AbstractJType; +import com.helger.jcodemodel.IJFormatter; +import com.helger.jcodemodel.JAnnotationUse; +import com.helger.jcodemodel.JMod; +import com.helger.jcodemodel.JMods; +import com.helger.jcodemodel.JVar; + +/// +/// A variable that is declared in the signature of a method +/// +/// - only allowed mod is final +/// - type is required +/// - No init expression +/// +public class JArgVar extends JVar { + + public JArgVar(boolean final_, @NonNull AbstractJType aType, @NonNull String sName) { + super(JMods.forVar(final_ ? JMod.NONE : JMod.FINAL), aType, sName, null); + } + + @Override + public void bind(@NonNull final IJFormatter f) { + for (final JAnnotationUse annotation : annotations()) { + f.generable(annotation); + f.print(' '); + } + f.generable(mods()); + bindType(f); + f.id(name()); + } + + // just here to be overridden for varargs + protected void bindType(@NonNull final IJFormatter f) { + f.generable(type()); + } + + @Override + public String separator() { + return ","; + } + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JBlockVar.java b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JBlockVar.java new file mode 100644 index 000000000..78040d8ac --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JBlockVar.java @@ -0,0 +1,101 @@ +package com.helger.jcodemodel.vars; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; + +import com.helger.jcodemodel.AbstractJType; +import com.helger.jcodemodel.IJDeclaration; +import com.helger.jcodemodel.IJFormatter; +import com.helger.jcodemodel.IVariableInitializer; +import com.helger.jcodemodel.JMods; +import com.helger.jcodemodel.JVar; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping; + +/// +/// A variable that is declared as part of a block. +/// +/// example : +/// ```java +/// int i=0; +/// ``` +/// +public class JBlockVar extends JVar implements IJDeclaration { + + private final List childrenVar = new ArrayList<>(); + + public JBlockVar(@NonNull JMods aMods, + AbstractJType aType, + @NonNull String sName, + @Nullable IVariableInitializer aInitExpr) { + super(aMods, aType, sName, aInitExpr); + } + + /// @return a stream of this and children variables. + public Stream streamVars() { + return Stream.concat(Stream.of(this), childrenVar.stream()); + } + + @Override + public void declare(@NonNull IJFormatter f) { + if (childrenVar.isEmpty()) { + super.declare(f); + } else { + f.vars( + streamVars().toList(), + extractWrappingOptions(f)) + .print(';').newline(); + } + } + + /// extract the wrapping options for this type of var. Present here to be + /// overridden in the fieldVar + protected ListWrapping extractWrappingOptions(@NonNull IJFormatter f) { + return f.settings().wrap.variables.block; + } + + /// add and return a new var with same type and mods, but given name and init. + /// + /// Note that the dimension is added on top of this' type. For example + /// ```java + /// int [] i={0}, j[][], k; + /// ``` + /// makes i an int[], j an int[][][] (dim 2), and k an int[] (dim 1). + /// + /// @param dim the additional dimension of the array, based on the type of this + public JSameVar andVar(String name, int dim, IVariableInitializer aInitExpr) { + JSameVar ret = new JSameVar(this, name, aInitExpr, dim); + childrenVar.add(ret); + return ret; + } + + /// add and return a new var with same type and mods, but given name and init. + /// + /// dimension is set to 0, meaning the new variable type is the same as this. + public JSameVar andVar(String name, IVariableInitializer aInitExpr) { + return andVar(name, 0, aInitExpr); + } + + /// add and return a new var with same type and mods, but given name and + /// dimension. + /// + /// init is set to null, so nonexistant assignment. + public JSameVar andVar(String name, int dim) { + return andVar(name, dim, null); + } + + /// add and return a new var with same type, same mods, but no init and given + /// name. Also with dimension 0 + public JSameVar andVar(String name) { + return andVar(name, null); + } + + @Override + public String separator() { + return ","; + } + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JCatchFormalParameter.java b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JCatchFormalParameter.java new file mode 100644 index 000000000..9296924f0 --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JCatchFormalParameter.java @@ -0,0 +1,58 @@ +package com.helger.jcodemodel.vars; + +import java.util.ArrayList; +import java.util.List; + +import org.jspecify.annotations.NonNull; + +import com.helger.jcodemodel.AbstractJClass; +import com.helger.jcodemodel.AbstractJType; +import com.helger.jcodemodel.IJFormatter; + +/// +/// A variable that is declared in a catch block +/// +/// - only allowed mod is final +/// - type is required, even though the actual type should be exception +/// - No init expression +/// +/// its type must be an abstractJClass since generics are not allowed +/// +/// Its internal type is the initial one, then set to null when new types are added, since it needs be deduced at compile. +/// +/// @see https://docs.oracle.com/javase/specs/jls/se25/html/jls-14.html#jls-14.20-510 +/// +public class JCatchFormalParameter extends JArgVar { + + /// list of types for the variable + private List m_lTypes = new ArrayList<>(); + + public JCatchFormalParameter(boolean final_, @NonNull AbstractJClass aType, @NonNull String sName) { + super(final_, aType, sName); + m_lTypes.add(aType); + } + + public JCatchFormalParameter addType(AbstractJClass type) { + if (type != null) { + type(type); + m_lTypes.add(type); + } + return this; + } + + @Override + public AbstractJClass type() { + return (AbstractJClass) super.type(); + } + + @Override + protected void bindType(@NonNull IJFormatter f) { + f.generable(m_lTypes, " | ", f.settings().wrap.catchClause.types); + } + + @Override + public String separator() { + throw new UnsupportedOperationException("can't declare two vars in a catch block"); + } + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JForEachVar.java b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JForEachVar.java new file mode 100644 index 000000000..9a33c1dc4 --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JForEachVar.java @@ -0,0 +1,72 @@ +package com.helger.jcodemodel.vars; + +import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; + +import com.helger.jcodemodel.AbstractJType; +import com.helger.jcodemodel.IJExpression; +import com.helger.jcodemodel.IJFormatter; +import com.helger.jcodemodel.JAnnotationUse; +import com.helger.jcodemodel.JMod; +import com.helger.jcodemodel.JMods; +import com.helger.jcodemodel.JVar; + +/// +/// a variable that is declared as part of a `for( type name : iterable)` +/// +/// when declared, it uses the required expression with ':' instead of '=', and does not add a semicolon. +/// +/// - only allowed mod is final. +/// - type can be null. In that case, "var" is used. +/// - name needs be provided. Can be relaxed later for "_" +/// - The init expression **must** be null +/// - a new **collection** property is used instead to store the iteration +/// +public class JForEachVar extends JVar { + + protected IJExpression collection; + + public JForEachVar(boolean isFinal, + @Nullable AbstractJType aType, + @NonNull String sName, + @NonNull IJExpression aCollection) { + super(JMods.forVar(isFinal ? JMod.FINAL : JMod.NONE), aType, sName, null); + collection = aCollection; + } + + public IJExpression collection() { + return collection; + } + + @Override + public @NonNull JForEachVar init(@Nullable IJExpression aInitExpr) { + if (aInitExpr != null) { + throw new UnsupportedOperationException(getClass().getSimpleName() + " can't receive a non-null init"); + } + return this; + } + + @Override + public void bind(@NonNull final IJFormatter f) { + for (final JAnnotationUse annotation : annotations()) { + f.generable(annotation); + f.print(' '); + } + f.generable(mods()); + if (type() != null) { + f.generable(type()); + } else { + f.print("var"); + } + f + .id(name()) + .print(':') + .generable(collection()); + } + + @Override + public String separator() { + throw new UnsupportedOperationException("can't declare two vars in a foreach loop"); + } + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JSameVar.java b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JSameVar.java new file mode 100644 index 000000000..7a11757f7 --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JSameVar.java @@ -0,0 +1,62 @@ +package com.helger.jcodemodel.vars; + +import org.jspecify.annotations.NonNull; + +import com.helger.jcodemodel.AbstractJType; +import com.helger.jcodemodel.IJFormatter; +import com.helger.jcodemodel.IVariableInitializer; +import com.helger.jcodemodel.JVar; + +/// vars that are the same as another one. +/// +/// example +/// ```java +/// int i=0, j, k=1; +/// ``` +/// Here i is a block variable, j and k are "same" var. +public class JSameVar extends JVar { + + private final JVar parent; + + /// number of additional array dimension on top of the parent. + private final int dim; + + public JSameVar(JVar parent, String sName, IVariableInitializer aInitExpr, int dim) { + super(parent.mods(), typeArray(parent.type(), dim), sName, aInitExpr); + this.parent = parent; + this.dim = dim; + } + + public JSameVar(JVar parent, String sName, IVariableInitializer aInitExpr) { + this(parent, sName, aInitExpr, 0); + } + + public JVar parentVar() { + return parent; + } + + @Override + public void bind(@NonNull IJFormatter f) { + f.id(name()); + for (int i = 0; i < dim; i++) { + f.print("[]"); + } + if (init() != null) { + f.print('=').generable(init()); + } + } + + @Override + public String separator() { + return ","; + } + + static AbstractJType typeArray(AbstractJType type, int dim) { + while (dim > 0) { + type = type.array(); + dim--; + } + return type; + } + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JVarArgVar.java b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JVarArgVar.java new file mode 100644 index 000000000..ef7ed24ec --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/vars/JVarArgVar.java @@ -0,0 +1,33 @@ +package com.helger.jcodemodel.vars; + +import org.jspecify.annotations.NonNull; + +import com.helger.jcodemodel.AbstractJType; +import com.helger.jcodemodel.IJFormatter; + +/// +/// A variable that is the last argument of a method signature, with variable length. +/// +/// same constraints as for the [JArgVar] +/// +public class JVarArgVar extends JArgVar { + + /// + /// @param aType the array type that this variable has. + public JVarArgVar(boolean final_, AbstractJType aType, @NonNull String sName) { + super(final_, aType, sName); + } + + @Override + protected void bindType(@NonNull IJFormatter f) { + f.generable(type().elementType()); + f.print("... "); + } + + @Override + public String separator() { + throw new UnsupportedOperationException("can't declare two varargs as method signature"); + } + + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/writer/FormatterSettings.java b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/FormatterSettings.java new file mode 100644 index 000000000..5cc14506c --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/FormatterSettings.java @@ -0,0 +1,73 @@ +package com.helger.jcodemodel.writer; + +import java.util.function.Consumer; + +import com.helger.jcodemodel.writer.settings.Indent; +import com.helger.jcodemodel.writer.settings.Wrap; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; +import com.helger.jcodemodel.writer.settings.Wrap.WordWrapping.EWordWrapStrategy; + +public class FormatterSettings { + + // + // help configs + // + + public static final Consumer CONF_PHELGER = settings -> { + settings.indent + .useSpaces (2) + .tabSize (2); + settings.wrap.method.args + .condition(EListWrapStrategy.REQUIRED); + settings.wrap.method.bracket + .condition(EWordWrapStrategy.ALWAYS); + }; + + public static FormatterSettings phelger() { + return new FormatterSettings().configure(CONF_PHELGER); + } + + public static final Consumer CONF_GLELOUET = settings -> { + settings.indent + .useTabs(1) + .tabSize(2); + settings.wrap.catchClause.types + .condition(EListWrapStrategy.BINARY) + .indent(2); + settings.wrap.forLoop.init + .condition(EListWrapStrategy.BINARY) + .indent(2); + settings.wrap.method.args + .condition(EListWrapStrategy.BINARY) + .indent(2); + settings.wrap.method.bracket + .condition(EWordWrapStrategy.NEVER); + settings.wrap.method.params + .condition(EListWrapStrategy.BINARY) + .indent(2); + settings.wrap.variables.block + .condition(EListWrapStrategy.BINARY) + .indent(2); + settings.wrap.variables.field + .condition(EListWrapStrategy.BINARY) + .indent(2); + }; + + public static FormatterSettings glelouet() { + return new FormatterSettings().configure(CONF_PHELGER); + } + + // + // + // + + public final Indent indent = new Indent(); + + public final Wrap wrap = new Wrap(); + + public FormatterSettings configure(Consumer conf) { + conf.accept(this); + return this; + } + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/writer/JCMWriter.java b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/JCMWriter.java index 64f9e4b73..9649daa20 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/writer/JCMWriter.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/JCMWriter.java @@ -89,10 +89,7 @@ public class JCMWriter /** The newline string to be used. Defaults to system default */ private String m_sNewLine = DEFAULT_NEW_LINE; - /** - * String to be used for each indentation. Defaults to four spaces. - */ - private String m_sIndentString = DEFAULT_INDENT_STRING; + private FormatterSettings m_aSettings = new FormatterSettings (); /** * Java feature (major release version) the generated code is targeted at. A feature that requires @@ -154,17 +151,20 @@ public JCMWriter setNewLine (@NonNull @Nonempty final String sNewLine) return this; } - @NonNull - public String getIndentString () + public FormatterSettings settings () { - return m_sIndentString; + return m_aSettings; } - @NonNull - public JCMWriter setIndentString (@NonNull final String sIndentString) + /// set the options, only if params not null. + /// @param options if null, not set (no effect) + /// @return this + public JCMWriter withSettings (FormatterSettings settings) { - ValueEnforcer.notNull (sIndentString, "IndentString"); - m_sIndentString = sIndentString; + if (settings != null) + { + m_aSettings = settings; + } return this; } @@ -222,9 +222,10 @@ public void build (@NonNull final File aDestDir, @Nullable final IProgressTracke * @throws IOException * on IO error if non-null, progress indication will be sent to this stream. */ - public void build (@NonNull final File aSrcDir, - @NonNull final File aResourceDir, - @Nullable final IProgressTracker aStatusPT) throws IOException + public void build ( + @NonNull final File aSrcDir, + @NonNull final File aResourceDir, + @Nullable final IProgressTracker aStatusPT) throws IOException { AbstractCodeWriter aSrcWriter = new FileCodeWriter (aSrcDir, m_aCharset, m_sNewLine); AbstractCodeWriter aResWriter = new FileCodeWriter (aResourceDir, m_aCharset, m_sNewLine); @@ -288,7 +289,7 @@ public void build (@NonNull final AbstractCodeWriter aWriter) throws IOException * on IO error */ public void build (@NonNull final AbstractCodeWriter aSourceWriter, @NonNull final AbstractCodeWriter aResourceWriter) - throws IOException + throws IOException { ValueEnforcer.notNull (aSourceWriter, "SourceWriter"); ValueEnforcer.notNull (aResourceWriter, "ResourceWriter"); @@ -298,12 +299,16 @@ public void build (@NonNull final AbstractCodeWriter aSourceWriter, @NonNull fin // Copy to avoid concurrent modification exception final List aPackages = m_aCM.getAllPackages (); for (final JPackage aPackage : aPackages) + { buildPackage (aSourceWriter, aPackage); + } // Write resources only final List aResourceDirs = m_aCM.getAllResourceDirs (); for (final JResourceDir aResourceDir : aResourceDirs) + { buildResourceDir (aResourceWriter, aResourceDir); + } } finally { @@ -313,12 +318,13 @@ public void build (@NonNull final AbstractCodeWriter aSourceWriter, @NonNull fin } @NonNull - private JFormatter _createJavaSourceFileWriter (@NonNull final AbstractCodeWriter aSrcWriter, - @NonNull final JPackage aPackage, - @NonNull final String sClassFilename) throws IOException + private JFormatter _createJavaSourceFileWriter ( + @NonNull final AbstractCodeWriter aSrcWriter, + @NonNull final JPackage aPackage, + @NonNull final String sClassFilename) throws IOException { final SourcePrintWriter aWriter = aSrcWriter.openSource (aPackage, sClassFilename); - final JFormatter ret = new JFormatter (aWriter, m_sIndentString); + final JFormatter ret = new JFormatter (aWriter, m_aSettings); ret.setJavaFeature (m_nJavaFeature); // Add all classes to not be imported (may be empty) ret.addDontImportClasses (m_aCM.getAllDontImportClasses ()); @@ -326,7 +332,7 @@ private JFormatter _createJavaSourceFileWriter (@NonNull final AbstractCodeWrite } public void buildPackage (@NonNull final AbstractCodeWriter aSourceWriter, @NonNull final JPackage aPackage) - throws IOException + throws IOException { ValueEnforcer.notNull (aSourceWriter, "SourceWriter"); ValueEnforcer.notNull (aPackage, "Package"); @@ -354,19 +360,24 @@ public void buildPackage (@NonNull final AbstractCodeWriter aSourceWriter, @NonN try (final IJFormatter f = _createJavaSourceFileWriter (aSourceWriter, aPackage, "package-info.java")) { if (!aJavaDoc.isEmpty ()) + { f.generable (aJavaDoc); + } // TODO: think about importing for (final JAnnotationUse a : aAnnotations) + { f.generable (a).newline (); + } f.declaration (aPackage); } } } - public void buildResourceDir (@NonNull final AbstractCodeWriter aResourceWriter, - @NonNull final JResourceDir aResourceDir) throws IOException + public void buildResourceDir ( + @NonNull final AbstractCodeWriter aResourceWriter, + @NonNull final JResourceDir aResourceDir) throws IOException { ValueEnforcer.notNull (aResourceWriter, "ResourceWriter"); ValueEnforcer.notNull (aResourceDir, "ResourceDir"); @@ -375,7 +386,7 @@ public void buildResourceDir (@NonNull final AbstractCodeWriter aResourceWriter, for (final AbstractJResourceFile rsrc : aResourceDir.getAllResourceFiles ()) { try (final OutputStream os = aResourceWriter.openBinary (aResourceDir.name (), rsrc.name ()); - final OutputStream bos = new BufferedOutputStream (os)) + final OutputStream bos = new BufferedOutputStream (os)) { rsrc.build (bos); } diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/writer/JFormatter.java b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/JFormatter.java index 728275e88..4065250a8 100644 --- a/jcodemodel/src/main/java/com/helger/jcodemodel/writer/JFormatter.java +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/JFormatter.java @@ -6,11 +6,11 @@ * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific + * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each @@ -30,10 +30,10 @@ * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a + * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code + * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. @@ -48,6 +48,8 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Function; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; @@ -57,18 +59,11 @@ import com.helger.annotation.WillCloseWhenClosed; import com.helger.annotation.concurrent.NotThreadSafe; import com.helger.base.enforce.ValueEnforcer; -import com.helger.jcodemodel.AbstractJClass; -import com.helger.jcodemodel.IJDeclaration; -import com.helger.jcodemodel.IJFormatter; -import com.helger.jcodemodel.IJGenerable; -import com.helger.jcodemodel.IJStatement; -import com.helger.jcodemodel.JAnonymousClass; -import com.helger.jcodemodel.JDefinedClass; -import com.helger.jcodemodel.JNarrowedClass; -import com.helger.jcodemodel.JPackage; -import com.helger.jcodemodel.JVar; +import com.helger.jcodemodel.*; import com.helger.jcodemodel.util.ClassNameComparator; import com.helger.jcodemodel.util.NullWriter; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; /** * This is a utility class for managing indentation and other basic formatting @@ -128,21 +123,17 @@ public boolean isAmbiguousIn (@NonNull final JDefinedClass aEnclosingClass) // special case where a generated type collides with a type in package // java.lang - if (aSingleRef._package () == JFormatter.this.m_aPckJavaLang) + if (aSingleRef._package () == m_aPckJavaLang) { // make sure that there's no other class with this name within the // same package for (final JDefinedClass aClass : aEnclosingClass._package ().classes ()) - { // even if this is the only "String" class we use, // if the class called "String" is in the same package, // we still need to import it. if (aClass.name ().equals (aSingleRef.name ())) - { // collision -> ambiguous return true; - } - } } return false; @@ -151,7 +142,9 @@ public boolean isAmbiguousIn (@NonNull final JDefinedClass aEnclosingClass) public boolean addReferencedType (@NonNull final AbstractJClass aClazz) { if (false) + { LOGGER.info ("Adding referenced type[" + m_sName + "]: " + aClazz.fullName ()); + } if (m_aReferencedClasses.contains (aClazz)) return false; return m_aReferencedClasses.add (aClazz); @@ -253,7 +246,7 @@ static boolean isJavaLangClass (final String sSimpleClassName) final Boolean ret = RESERVERD_JAVA_LANG_NAME.get (sSimpleClassName); if (ret != null) - return ret.booleanValue (); + return ret; boolean bIsJavaLang = true; try @@ -264,7 +257,7 @@ static boolean isJavaLangClass (final String sSimpleClassName) { bIsJavaLang = false; } - RESERVERD_JAVA_LANG_NAME.put (sSimpleClassName, Boolean.valueOf (bIsJavaLang)); + RESERVERD_JAVA_LANG_NAME.put (sSimpleClassName, bIsJavaLang); return bIsJavaLang; } @@ -282,10 +275,8 @@ private AbstractJClass _getClassForImport (@Nullable final AbstractJClass aClass { AbstractJClass aRealClass = aClass; if (aRealClass instanceof JAnonymousClass) - { // get the super class of the anonymous class - return _getClassForImport (((JAnonymousClass) aRealClass).base ()); - } + return _getClassForImport ( ((JAnonymousClass) aRealClass).base ()); if (aRealClass instanceof JNarrowedClass) { // Never imported narrowed class but the erasure only @@ -308,7 +299,9 @@ public boolean add (@NonNull final AbstractJClass aClass) if (m_aDontImportClasses.contains (aRealClass)) { if (m_bDebugImport) + { LOGGER.info ("The class '" + aRealClass.fullName () + "' should not be imported!"); + } return false; } @@ -316,19 +309,25 @@ public boolean add (@NonNull final AbstractJClass aClass) if (!m_aNames.add (sSimpleName)) { if (m_bDebugImport) + { LOGGER.info ("A class with local name '" + sSimpleName + "' is already in the import list."); + } return false; } if (!m_aClasses.add (aRealClass)) { if (m_bDebugImport) + { LOGGER.info ("The class '" + aRealClass.fullName () + "' is already in the import list."); + } return false; } if (m_bDebugImport) + { LOGGER.info ("Added import class '" + aClass.fullName () + "'"); + } return true; } @@ -374,23 +373,84 @@ public List getAllSorted () */ private EMode m_eMode = EMode.PRINTING; - /** - * Current number of indentation strings to print - */ - private int m_nIndentLevel; - - /** - * String to be used for each indentation. Defaults to four spaces. - */ - private final String m_sIndentString; + private final FormatterSettings m_oSettings; /** * Writer associated with this {@link IJFormatter} */ private final SourcePrintWriter m_aPW; - private char m_cLastChar = 0; - private boolean m_bAtBeginningOfLine = true; + /// contexts to write into instead of the printwriter. + /// + /// No context should be kept here after closed. + private final List m_aContextLayers = new ArrayList <> (); + + /// internal field to have this as a writer context. + final WriteContext asContext = new WriteContext () + { + + /** + * Current number of indentation strings to print + */ + private int m_nIndentLevel; + + private char m_cLastChar = 0; + + @NonNull + private StringBuilder currentLine = new StringBuilder (); + + @Override + public int getIndentLevel () + { + return m_nIndentLevel; + } + + @Override + public void setIndentLevel (int nb) + { + m_nIndentLevel = nb; + } + + @Override + public char getLastChar () + { + return m_cLastChar; + } + + @Override + public String getCurrentLine () + { + return currentLine.toString (); + } + + @Override + public String getNewLine () + { + return JFormatter.this.getNewLine (); + } + + @Override + public void append (String fullString, boolean resetLine, String appendLine, char lastChar) + { + m_aPW.print (fullString); + m_cLastChar = lastChar; + if (resetLine) + { + currentLine = new StringBuilder (); + } + currentLine.append (appendLine); + } + + @Override + public void append (char c) + { + char printedChar = c == CLOSE_TYPE_ARGS ? '>' : c; + m_aPW.print (printedChar); + currentLine.append (printedChar); + m_cLastChar = c; + } + }; + private JPackage m_aPckJavaLang; /** @@ -413,18 +473,20 @@ public List getAllSorted () * Incremental indentation string, similar to tab value. May not be * null. */ - public JFormatter (@NonNull @WillCloseWhenClosed final SourcePrintWriter aPW, @NonNull final String sIndentString) + public JFormatter (@NonNull @WillCloseWhenClosed final SourcePrintWriter aPW, + @NonNull final FormatterSettings formatterSettings) { ValueEnforcer.notNull (aPW, "PrintWriter"); - ValueEnforcer.notNull (sIndentString, "IndentString"); + ValueEnforcer.notNull (formatterSettings, "formatterSettings"); m_aPW = aPW; - m_sIndentString = sIndentString; + m_oSettings = formatterSettings; } /** * Closes this formatter. */ + @Override public void close () { m_aPW.close (); @@ -462,28 +524,38 @@ public JFormatter setJavaFeature (final int nJavaFeature) m_nJavaFeature = nJavaFeature; return this; } - - public String getNewLine() + + @Override + public String getNewLine () + { + return m_aPW.getNewLine (); + } + + @Override + public FormatterSettings settings () { - return m_aPW.getNewLine(); + return m_oSettings; } + @Override public boolean isPrinting () { return m_eMode == EMode.PRINTING; } + @Override @NonNull - public JFormatter indent () + public JFormatter indent (int nb) { - m_nIndentLevel++; + topContext ().indent (nb); return this; } + @Override @NonNull - public JFormatter outdent () + public JFormatter outdent (int nb) { - m_nIndentLevel--; + topContext ().outdent (nb); return this; } @@ -497,10 +569,8 @@ private static boolean _needSpace (final char c1, final char c2) { // e.g., "public Foo test;" if (c2 == '(') - { // but not "new Foo()" return false; - } return true; } if ((c1 == ')') && (c2 == '{')) @@ -519,28 +589,28 @@ private static boolean _needSpace (final char c1, final char c2) { switch (c2) { - case '{': - case '}': - case '+': - case '-': - case '>': - case '@': - return true; - default: - return Character.isJavaIdentifierStart (c2); + case '{': + case '}': + case '+': + case '-': + case '>': + case '@': + return true; + default: + return Character.isJavaIdentifierStart (c2); } } if (Character.isJavaIdentifierStart (c2)) { switch (c1) { - case ']': - case ')': - case '}': - case '+': - return true; - default: - return false; + case ']': + case ')': + case '}': + case '+': + return true; + default: + return false; } } if (Character.isDigit (c2)) @@ -554,136 +624,144 @@ private static boolean _needSpace (final char c1, final char c2) private void _spaceIfNeeded (final char c) { - if (m_bAtBeginningOfLine) + if (atBeginningOfLine ()) { - for (int i = 0; i < m_nIndentLevel; i++) - m_aPW.print (m_sIndentString); - m_bAtBeginningOfLine = false; + for (int i = 0; i < indentLevel (); i++) + { + topContext ().append (m_oSettings.indent.string ()); + } + } + else if ((lastChar () != 0) && _needSpace (lastChar (), c)) + { + topContext ().append (' '); } - else - if (m_cLastChar != 0 && _needSpace (m_cLastChar, c)) - m_aPW.print (' '); } + @Override @NonNull public JFormatter print (final char c) { if (m_eMode == EMode.PRINTING) { - if (c == CLOSE_TYPE_ARGS) - { - m_aPW.print ('>'); - } - else + if (c != CLOSE_TYPE_ARGS) { _spaceIfNeeded (c); - m_aPW.print (c); } - m_cLastChar = c; + topContext ().append (c); } return this; } + @Override @NonNull public JFormatter print (@NonNull final String sStr) { - if (m_eMode == EMode.PRINTING && sStr.length () > 0) + if ((m_eMode == EMode.PRINTING) && (sStr.length () > 0)) { _spaceIfNeeded (sStr.charAt (0)); - m_aPW.print (sStr); - m_cLastChar = sStr.charAt (sStr.length () - 1); + topContext ().append (sStr); } return this; } + @Override @NonNull public JFormatter type (@NonNull final AbstractJClass aType) { switch (m_eMode) { - case COLLECTING: - if (!aType.isError ()) + case COLLECTING: + if (!aType.isError ()) + { + final String sShortName = aType.name (); + m_aCollectedReferences.computeIfAbsent (sShortName, k -> new NameUsage (sShortName)).addReferencedType (aType); + } + break; + case PRINTING: + if (aType.isError ()) + { + print ("Object"); + } + else + { + // many of the JTypes in this list are either primitive or belong to + // package java so we don't need a FQCN + final boolean bCanUseShortName; + if (m_aImportedClasses.contains (aType)) { - final String sShortName = aType.name (); - m_aCollectedReferences.computeIfAbsent (sShortName, k -> new NameUsage (sShortName)).addReferencedType (aType); + bCanUseShortName = true; } - break; - case PRINTING: - if (aType.isError ()) + else if (aType._package () == m_aPckJavaLang) { - print ("Object"); + bCanUseShortName = _isUnambiguousJavaLangImport (aType); } else { - // many of the JTypes in this list are either primitive or belong to - // package java so we don't need a FQCN - final boolean bCanUseShortName; - if (m_aImportedClasses.contains (aType)) - bCanUseShortName = true; - else - if (aType._package () == m_aPckJavaLang) - bCanUseShortName = _isUnambiguousJavaLangImport (aType); - else - bCanUseShortName = false; + bCanUseShortName = false; + } - if (bCanUseShortName) + if (bCanUseShortName) + { + // FQCN imported or not necessary, so generate short name + print (aType.name ()); + } + else + { + final AbstractJClass aOuter = aType.outer (); + if (aOuter != null) { - // FQCN imported or not necessary, so generate short name - print (aType.name ()); + type (aOuter).print ('.').print (aType.name ()); } else + // collision was detected, so generate FQCN { - final AbstractJClass aOuter = aType.outer (); - if (aOuter != null) - { - type (aOuter).print ('.').print (aType.name ()); - } - else - { - // collision was detected, so generate FQCN - print (aType.fullName ()); - } + // collision was detected, so generate FQCN + print (aType.fullName ()); } } - break; - case FIND_ERROR_TYPES: - if (aType.isError ()) - m_bContainsErrorTypes = true; - break; + } + break; + case FIND_ERROR_TYPES: + if (aType.isError ()) + { + m_bContainsErrorTypes = true; + } + break; } return this; } + @Override @NonNull public JFormatter id (@NonNull final String sID) { switch (m_eMode) { - case COLLECTING: - // see if there is a type name that collides with this id - // not a type, but we need to create a place holder to - // see if there might be a collision with a type - m_aCollectedReferences.computeIfAbsent (sID, NameUsage::new).setVariableName (); - break; - case PRINTING: - print (sID); - break; + case COLLECTING: + // see if there is a type name that collides with this id + // not a type, but we need to create a place holder to + // see if there might be a collision with a type + m_aCollectedReferences.computeIfAbsent (sID, NameUsage::new).setVariableName (); + break; + case PRINTING: + print (sID); + break; } return this; } + @Override @NonNull public JFormatter newline () { if (m_eMode == EMode.PRINTING) { - m_aPW.println (); - m_cLastChar = 0; - m_bAtBeginningOfLine = true; + topContext ().append (getNewLine ()); } return this; } + @Override @NonNull public JFormatter generable (@NonNull final IJGenerable g) { @@ -692,7 +770,7 @@ public JFormatter generable (@NonNull final IJGenerable g) } @NonNull - public JFormatter generable (@NonNull final Collection list) + public JFormatter generableLegacy (@NonNull final Collection list, String separator) { if (!list.isEmpty ()) { @@ -700,7 +778,9 @@ public JFormatter generable (@NonNull final Collection l for (final IJGenerable item : list) { if (!bFirst) - print (','); + { + print (separator); + } generable (item); bFirst = false; } @@ -708,6 +788,34 @@ public JFormatter generable (@NonNull final Collection l return this; } + @Override + public @NonNull IJFormatter generable ( + @NonNull Collection aList, + String separator, + ListWrapping wrapping) + { + if (settings ().wrap.disabled) + return generableLegacy (aList, separator); + EListWrapStrategy selectedWrap = EListWrapStrategy.NEVER; + if (wrapping != null) + { + selectedWrap = wrapping.condition; + } + int indentParam = 1; + if (wrapping != null) + { + indentParam = wrapping.indent; + } + boolean wrapAfterSep = true; + if (wrapping != null) + { + wrapAfterSep = wrapping.wrapAfterSep; + } + genericPrints (aList, selectedWrap, wrapAfterSep, o -> separator, indentParam, this::generable); + return this; + } + + @Override @NonNull public JFormatter declaration (@NonNull final IJDeclaration d) { @@ -715,6 +823,7 @@ public JFormatter declaration (@NonNull final IJDeclaration d) return this; } + @Override @NonNull public JFormatter statement (@NonNull final IJStatement aStmt) { @@ -722,6 +831,7 @@ public JFormatter statement (@NonNull final IJStatement aStmt) return this; } + @Override @NonNull public JFormatter var (@NonNull final JVar aVar) { @@ -729,10 +839,148 @@ public JFormatter var (@NonNull final JVar aVar) return this; } - private boolean _collectCausesNoAmbiguities (@NonNull final AbstractJClass aReference, @NonNull final JDefinedClass aClassToBeWritten) + @Override + public IJFormatter vars (@NonNull final Collection aList, ListWrapping wrapping) + { + EListWrapStrategy wrapCondition = EListWrapStrategy.PAST3; + if (wrapping != null) + { + wrapCondition = wrapping.condition; + } + int indentParam = 1; + if (wrapping != null) + { + indentParam = wrapping.indent; + } + boolean wrapAfterSep = true; + if (wrapping != null) + { + wrapAfterSep = wrapping.wrapAfterSep; + } + + genericPrints (aList, wrapCondition, wrapAfterSep, JVar::separator, indentParam, this::var); + return this; + } + + /// print a collection with wrapping strategy + protected JFormatter genericPrints ( + @NonNull final Collection aList, + @NonNull EListWrapStrategy selectedWrap, + boolean wrapAFterSep, + Function separator, + int indentValue, + Consumer elementPrinter) + { + // if PAST3 and less equal 3 params, replace with NEVER. + if ((selectedWrap == EListWrapStrategy.PAST3) && (aList.size () <= 3)) + { + selectedWrap = EListWrapStrategy.NEVER; + } + // for BINARY, try NEVER ; then if the produced line size is too big or + // has newline, rollback and use ALWAYS instead. + if (selectedWrap == EListWrapStrategy.BINARY) + { + try (IContextCloser o = addContextLayer ().persistOnClose ()) + { + genericPrintsStatic (aList, EListWrapStrategy.NEVER, wrapAFterSep, separator, indentValue, elementPrinter); + if (o.value ().contains (getNewLine ()) || (currentLineSize () > settings ().wrap.lineWidth)) + { + o.rollback (); + selectedWrap = EListWrapStrategy.ALWAYS; + } + else + return this; + } + } + genericPrintsStatic (aList, selectedWrap, wrapAFterSep, separator, indentValue, elementPrinter); + return this; + } + + /// print several items with one-pass strategy. + /// @param elementPrinter what should we do with each element + protected JFormatter genericPrintsStatic ( + @NonNull final Iterable aList, + @NonNull EListWrapStrategy selectedWrap, + boolean wrapAFterSep, + Function separator, + int indentValue, + Consumer elementPrinter) + { + if (selectedWrap.twoPasses) + throw new RuntimeException ("this method can't accept two-passes config " + selectedWrap); + T last = null; + boolean indented = false; + for (final T element : aList) + { + if (last == null) + { + last = element; + if ((selectedWrap == EListWrapStrategy.ALWAYS) && !currentLine ().isBlank ()) + { + newline (); + indented = true; + indent (indentValue); + } + if (selectedWrap == EListWrapStrategy.PAST3) + { + selectedWrap = EListWrapStrategy.ALWAYS; + } + } + else + { + String sep = separator.apply (last); + if (wrapAFterSep) + { + print (sep); + } + if (selectedWrap == EListWrapStrategy.REQUIRED) + { + try (IContextCloser o = addContextLayer ().persistOnClose ()) + { + elementPrinter.accept (element); + if (o.value ().contains (getNewLine ()) || (currentLineSize () > settings ().wrap.lineWidth)) + { + o.rollback (); + newline (); + } + else + { + continue; + } + } + } + else if (selectedWrap == EListWrapStrategy.ALWAYS) + { + newline (); + } + if (!wrapAFterSep) + { + print (sep); + } + } + elementPrinter.accept (element); + if (!indented) + { + indented = true; + indent (indentValue); + } + } + if (indented) + { + outdent (indentValue); + } + return this; + } + + private boolean _collectCausesNoAmbiguities ( + @NonNull final AbstractJClass aReference, + @NonNull final JDefinedClass aClassToBeWritten) { if (m_bDebugImport) - LOGGER.info ("_collectCausesNoAmbiguities(" + aReference.fullName () + ", " + aClassToBeWritten.fullName () + ")"); + { + LOGGER + .info ("_collectCausesNoAmbiguities(" + aReference.fullName () + ", " + aClassToBeWritten.fullName () + ")"); + } final NameUsage aUsages = m_aCollectedReferences.get (aReference.name ()); if (aUsages == null) @@ -751,10 +999,14 @@ private boolean _collectCausesNoAmbiguities (@NonNull final AbstractJClass aRefe * @return true if an import statement can be used to shorten * references to referenced class */ - private boolean _collectShouldBeImported (@NonNull final AbstractJClass aReference, @NonNull final JDefinedClass aClassToBeWritten) + private boolean _collectShouldBeImported ( + @NonNull final AbstractJClass aReference, + @NonNull final JDefinedClass aClassToBeWritten) { if (m_bDebugImport) + { LOGGER.info ("_collectShouldBeImported(" + aReference.fullName () + ", " + aClassToBeWritten.fullName () + ")"); + } AbstractJClass aRealReference = aReference; if (aRealReference instanceof JAnonymousClass) @@ -777,11 +1029,9 @@ private boolean _collectShouldBeImported (@NonNull final AbstractJClass aReferen // In such case no information is lost when we refer to inner class // without mentioning it's enclosing class if (aRealReference.name ().contains (aOuter.name ())) - { // Recurse if (_collectShouldBeImported (aOuter, aClassToBeWritten)) return true; - } // Do not import inner classes in all other cases to aid // understandability/readability. @@ -799,25 +1049,29 @@ private boolean _collectShouldBeImported (@NonNull final AbstractJClass aReferen * @param aClassToBeWritten * {@link AbstractJClass} that is the current class being processed */ - private void _collectImportOuterClassIfCausesNoAmbiguities (@NonNull final AbstractJClass aReference, - @NonNull final JDefinedClass aClassToBeWritten) + private void _collectImportOuterClassIfCausesNoAmbiguities ( + @NonNull final AbstractJClass aReference, + @NonNull final JDefinedClass aClassToBeWritten) { if (m_bDebugImport) - LOGGER.info ("_collectImportOuterClassIfCausesNoAmbiguities(" + aReference.fullName () + ", " + aClassToBeWritten.fullName () + ")"); + { + LOGGER.info ("_collectImportOuterClassIfCausesNoAmbiguities(" + aReference.fullName () + ", " + + aClassToBeWritten.fullName () + ")"); + } final AbstractJClass aOuter = aReference.outer (); if (aOuter != null) - { - if (_collectCausesNoAmbiguities (aOuter, aClassToBeWritten) && _collectShouldBeImported (aOuter, aClassToBeWritten)) + if (_collectCausesNoAmbiguities (aOuter, aClassToBeWritten) + && _collectShouldBeImported (aOuter, aClassToBeWritten)) { m_aImportedClasses.add (aOuter); } else + // Recursive call { // Recursive call _collectImportOuterClassIfCausesNoAmbiguities (aOuter, aClassToBeWritten); } - } } private boolean _isUnambiguousJavaLangImport (@NonNull final AbstractJClass aJavaLangReference) @@ -838,15 +1092,21 @@ private boolean _isUnambiguousJavaLangImport (@NonNull final AbstractJClass aJav * determine if an import statement should be suppressed * * @param aReference - * {@link AbstractJClass} that may or may not have an import + * {@link AbstractJClass} that may or may not have an + * import * @param aClassToBeWrittem - * {@link AbstractJClass} that is the current class being processed + * {@link AbstractJClass} that is the current class + * being processed * @return true if an import statement should be suppressed, false otherwise */ - private boolean _printIsImplicitlyImported (@NonNull final AbstractJClass aReference, @NonNull final AbstractJClass aClassToBeWrittem) + private boolean _printIsImplicitlyImported ( + @NonNull final AbstractJClass aReference, + @NonNull final AbstractJClass aClassToBeWrittem) { if (m_bDebugImport) + { LOGGER.info ("_printIsImplicitlyImported(" + aReference.fullName () + ", " + aClassToBeWrittem.fullName () + ")"); + } AbstractJClass aRealReference = aReference; if (aRealReference instanceof JAnonymousClass) @@ -862,33 +1122,25 @@ private boolean _printIsImplicitlyImported (@NonNull final AbstractJClass aRefer final JPackage aPackage = aRealReference._package (); if (aPackage == null) - { // May be null for JTypeVar and JTypeWildcard return true; - } if (aPackage.isUnnamed ()) - { // Root package - no need to import something return true; - } if (aPackage == m_aPckJavaLang) - { // no need to explicitly import java.lang classes return true; - } // All pkg local classes do not need an // import stmt for ref, except for inner classes if (aPackage == aClassToBeWrittem._package ()) { AbstractJClass aOuter = aRealReference.outer (); - if (aOuter == null) // top-level class - { + if (aOuter == null) // top-level package-local class needs no explicit import return true; - } // inner-class AbstractJClass aTopLevelClass = aOuter; @@ -925,7 +1177,9 @@ void writeClassFull (@NonNull final JDefinedClass aClassToBeWritten) declaration (aClassToBeWritten); if (m_bDebugImport) + { LOGGER.info ("***Start collecting***"); + } // the class itself that we will be generating is always accessible and must // be the first import @@ -934,7 +1188,6 @@ void writeClassFull (@NonNull final JDefinedClass aClassToBeWritten) // collate type names and identifiers to determine which types can be // imported for (final NameUsage aUsage : m_aCollectedReferences.values ()) - { if (!aUsage.isAmbiguousIn (aClassToBeWritten) && !aUsage.isVariableName ()) { final AbstractJClass aReferencedClass = aUsage.getSingleReferencedType (); @@ -948,18 +1201,18 @@ void writeClassFull (@NonNull final JDefinedClass aClassToBeWritten) _collectImportOuterClassIfCausesNoAmbiguities (aReferencedClass, aClassToBeWritten); } } - else + else if (aUsage.isTypeName ()) { - if (aUsage.isTypeName ()) - for (final AbstractJClass reference : aUsage.getReferencedTypes ()) - { - _collectImportOuterClassIfCausesNoAmbiguities (reference, aClassToBeWritten); - } + for (final AbstractJClass reference : aUsage.getReferencedTypes ()) + { + _collectImportOuterClassIfCausesNoAmbiguities (reference, aClassToBeWritten); + } } - } if (m_bDebugImport) + { LOGGER.info ("***Finished collecting***"); + } // then print the declaration m_eMode = EMode.PRINTING; @@ -968,7 +1221,9 @@ void writeClassFull (@NonNull final JDefinedClass aClassToBeWritten) // Header before package if (aClassToBeWritten.hasHeaderComment ()) + { generable (aClassToBeWritten.headerComment ()); + } // Emit the package name (if not empty) final JPackage aPackage = (JPackage) aClassToBeWritten.parentContainer (); @@ -980,7 +1235,6 @@ void writeClassFull (@NonNull final JDefinedClass aClassToBeWritten) // generate import statements boolean bAnyImport = false; for (final AbstractJClass aImportClass : m_aImportedClasses.getAllSorted ()) - { // suppress import statements for primitive types, built-in types, // types in the root package, and types in // the same package as the current type @@ -990,12 +1244,15 @@ void writeClassFull (@NonNull final JDefinedClass aClassToBeWritten) bAnyImport = true; if (m_bDebugImport) + { LOGGER.info (" import " + aImportClass.fullName ()); + } } - } if (bAnyImport) + { newline (); + } declaration (aClassToBeWritten); } @@ -1010,13 +1267,18 @@ void writeClassFull (@NonNull final JDefinedClass aClassToBeWritten) void addDontImportClasses (@Nullable final Iterable aClasses) { if (aClasses != null) + { for (final AbstractJClass aClass : aClasses) + { m_aImportedClasses.addDontImportClass (aClass); + } + } } public static boolean containsErrorTypes (@NonNull final JDefinedClass aClass) { - try (final JFormatter aFormatter = new JFormatter (new SourcePrintWriter (NullWriter.getInstance (), "\n"), "\t")) + try (final JFormatter aFormatter = new JFormatter (new SourcePrintWriter (NullWriter.getInstance (), "\n"), + new FormatterSettings ().configure (o -> o.indent.useTabs ()))) { aFormatter.m_eMode = EMode.FIND_ERROR_TYPES; aFormatter.m_bContainsErrorTypes = false; @@ -1024,4 +1286,266 @@ public static boolean containsErrorTypes (@NonNull final JDefinedClass aClass) return aFormatter.m_bContainsErrorTypes; } } + + /// @return the current line being written, in a buffer or in the printstream + public String currentLine () + { + return topContext ().getCurrentLine (); + } + + public char lastChar () + { + return topContext ().getLastChar (); + } + + public int indentLevel () + { + return topContext ().getIndentLevel (); + } + + public boolean atBeginningOfLine () + { + return currentLine ().isEmpty (); + } + + @Override + public int currentLineSize () + { + return sizeWithTabsExpanded (currentLine (), m_oSettings.indent.tabSize); + } + + /// computes the size of a string when tabs are expanded to match column size. + /// @param s the string to expand + /// @param tabSize size of a column a tab expands into. + // package-protected for tests + static int sizeWithTabsExpanded (String s, int columnSize) + { + if ((s == null) || s.isEmpty ()) + return 0; + int tabIndent = 0; + for (int i = 0; i < s.length (); i++) + if (s.charAt (i) == '\t') + { + int modtab = (i + 1 + tabIndent) % columnSize; + if (modtab > 0) + { + tabIndent += columnSize - modtab; + } + } + return s.length () + tabIndent; + + } + + // + // contexts management + // + + /// internal notion of writer context + interface WriteContext + { + + int getIndentLevel (); + + void setIndentLevel (int nb); + + char getLastChar (); + + default void indent (int nb) + { + setIndentLevel (getIndentLevel () + nb); + } + + default void outdent (int nb) + { + setIndentLevel (getIndentLevel () - nb); + } + + String getCurrentLine (); + + String getNewLine (); + + default void append (String sStr) + { + if ((sStr == null) || sStr.isEmpty ()) + return; + char lastChar = 0; + boolean resetLine = false; + String appendLine = null; + if (sStr.contains (getNewLine ())) + { + resetLine = true; + int offset = sStr.lastIndexOf (getNewLine ()) + getNewLine ().length (); + appendLine = sStr.substring (offset); + lastChar = appendLine.isEmpty () ? 0 : appendLine.charAt (appendLine.length () - 1); + } + else + { + appendLine = sStr; + lastChar = sStr.charAt (sStr.length () - 1); + } + + append (sStr, resetLine, appendLine, lastChar); + } + + void append (String fullString, boolean resetLine, String appendLine, char lastChar); + + void append (char c); + } + + /// Represents a context layer that *should* be automatically removed outside of + /// its declaration scope, using try-with-resource syntax. + /// + /// Defaults to a discarding context, so any data added to the formatter while + /// context active is discarded once the resource is closed. This can be changed + /// with #persistOnClose or simply committing the data wit #commit + /// + /// The #close method does not throw exception to have it simpler in the + /// try-declaration. It also only applies once, as encouraged by + /// [AutoCloseable#close] . + /// + /// This also contains a #currentLine that is copied from the underlying buffer + /// (or JFormatter if none), then updated like the JFormater is ; same for + /// lastchar and beginning of line + /// + /// This class is not thread safe. + // not static to directly access the fields and methods + class FormatterContext implements IContextCloser, WriteContext + { + + // public final, so no getter/setter + public final StringBuilder buffer; + + StringBuilder currentLine = new StringBuilder (currentLine ()); + + private char m_cLastChar = lastChar (); + + private int m_nIndentLevel = indentLevel (); + + /// when set to true, upon first #close, the context is re written into the + /// formatter, or into the next context if any. + boolean persistOnClose = false; + + boolean closed = false; + + // construct + + public FormatterContext (StringBuilder buffer) + { + this.buffer = buffer; + } + + public FormatterContext () + { + this (new StringBuilder ()); + } + + // getters/setters + + @Override + public String value () + { + return buffer.toString (); + } + + @Override + public String getCurrentLine () + { + return currentLine.toString (); + } + + @Override + public char getLastChar () + { + return m_cLastChar; + } + + @Override + public int getIndentLevel () + { + return m_nIndentLevel; + } + + @Override + public void setIndentLevel (int nb) + { + m_nIndentLevel = nb; + } + + /// @return true after #close has been called at least once. + @Override + public boolean isClosed () + { + return closed; + } + + @Override + public String getNewLine () + { + return JFormatter.this.getNewLine (); + } + + // other methods + + @Override + public FormatterContext persistOnClose (boolean b) + { + persistOnClose = b; + return this; + } + + @Override + public void close () + { + if (closed) + return; + m_aContextLayers.remove (this); + if (persistOnClose) + { + // printing the buffer will update the last char and current line in the next + // context. + topContext ().append (buffer.toString ()); + topContext ().setIndentLevel (getIndentLevel ()); + } + closed = true; + } + + @Override + public void append (String fullString, boolean resetLine, String lastLine, char lastChar) + { + buffer.append (fullString); + m_cLastChar = lastChar; + if (resetLine) + { + currentLine = new StringBuilder (); + } + currentLine.append (lastLine); + } + + @Override + public void append (char c) + { + char printedChar = c == CLOSE_TYPE_ARGS ? '>' : c; + buffer.append (printedChar); + currentLine.append (printedChar); + m_cLastChar = c; + } + } + + /// @return the top (last) context, if any ; or this as a writer context if + /// none. + protected WriteContext topContext () + { + return m_aContextLayers.isEmpty () ? asContext : m_aContextLayers.get (0); + } + + /// + /// @return a new [FormatterContext], put on top of the previous ones to receive + /// incoming writes. + @Override + public IContextCloser addContextLayer () + { + FormatterContext ret = new FormatterContext (); + m_aContextLayers.add (0, ret); + return ret; + } } diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/Indent.java b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/Indent.java new file mode 100644 index 000000000..c6baaf033 --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/Indent.java @@ -0,0 +1,59 @@ +package com.helger.jcodemodel.writer.settings; + +import org.jspecify.annotations.NonNull; + +import com.helger.jcodemodel.writer.JCMWriter; + +/// +/// recommended way to set indentation is to call #useSpaces or #useTabs ; but can directly set the string. +/// +public class Indent { + + public String string = JCMWriter.DEFAULT_INDENT_STRING; + + /// how many spaces do we consider a tab to take + public int tabSize = 4; + + public Indent useSpaces(int nb) { + string = " ".repeat(nb); + return this; + } + + /// defaults to 4 spaces + public Indent useSpaces() { + return useSpaces(4); + } + + public Indent useTabs(int nb) { + string = "\t".repeat(nb); + return this; + } + + /// defaults to 1 tab + public Indent useTabs() { + return useTabs(1); + } + + public String string() { + return string; + } + + public Indent withString(@NonNull String string) { + if (string == null || string.isEmpty()) { + this.string = ""; + } else { + this.string = string; + } + return this; + } + + public Indent tabSize(int size) { + tabSize = size; + return this; + } + + public int tabSize() { + return tabSize; + } + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/Wrap.java b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/Wrap.java new file mode 100644 index 000000000..ae223c579 --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/Wrap.java @@ -0,0 +1,142 @@ +package com.helger.jcodemodel.writer.settings; + +import com.helger.jcodemodel.writer.settings.wrap.CatchClause; +import com.helger.jcodemodel.writer.settings.wrap.ForLoop; +import com.helger.jcodemodel.writer.settings.wrap.Method; +import com.helger.jcodemodel.writer.settings.wrap.Variables; + +public class Wrap { + + /// configuration of a generated code's word wrapping : when to wrap it, how + /// many + /// indent. + /// + /// This is a generic idea for any one-time element, like the "implements" part + /// of a class, a method's return type, etc. + public static class WordWrapping { + + public enum EWordWrapStrategy { + /// always wrap the element + ALWAYS(), + /// never wrap + NEVER(), + /// only wrap if otherwise would go over the line size. + REQUIRED(); + } + + /// when do we wrap this specific code generation + public EWordWrapStrategy condition = EWordWrapStrategy.NEVER; + + /// when we wrap, how much do we indent the code + public int indent = 1; + + public WordWrapping condition(EWordWrapStrategy value) { + if (value != null) { + condition = value; + } + return this; + } + + public WordWrapping indent(int value) { + indent = value; + return this; + } + + } + + /// configuration of a generated code's elements wrapping : when to wrap the + /// elements, how many indent. + /// + /// This is a generic idea for list of elements which can be wrapped + /// individually, like the list of interfaces implemented by a class, its list + /// of Generics, etc. + public static class ListWrapping { + + public enum EListWrapStrategy { + /// always wrap all the elements + ALWAYS(false), + /// never wrap any element. All on the same line + NEVER(false), + /// only the minimum number of elements. + REQUIRED(false), + /// once an element should be wrapped, all are. + BINARY(true), + /// wrap all if more than 3 elements ; first item never wrapped + PAST3(false); + + public final boolean twoPasses; + + EListWrapStrategy(boolean twoPasses) { + this.twoPasses = twoPasses; + } + + } + + /// when do we wrap this specific code generation + public EListWrapStrategy condition = EListWrapStrategy.PAST3; + + /// when we wrap, how much do we indent the code + public int indent = 1; + + /// when false, we wrap before the separator + public boolean wrapAfterSep = true; + + public ListWrapping condition(EListWrapStrategy value) { + if (value != null) { + condition = value; + } + return this; + } + + public ListWrapping indent(int value) { + indent = value; + return this; + } + + public ListWrapping wrapAfterSep(boolean value) { + wrapAfterSep = value; + return this; + } + + public ListWrapping wrapBeforeSep() { + return wrapAfterSep(false); + } + + public ListWrapping wrapAfterSep () + { + return wrapAfterSep (true); + } + + } + + /// wrapping is required if an element would increase the line above + /// this number of characters + public int lineWidth = 80; + + public Wrap lineWidth(int value) { + lineWidth = value; + return this; + } + + /// feature flag. When set to true, all wrapping methods should be replaced with + /// wrapping-oblivious ones. + public boolean disabled = false; + + public Wrap disable(boolean value) { + disabled = value; + return this; + } + + public Wrap disable() { + return disable(true); + } + + public final CatchClause catchClause = new CatchClause(); + + public final ForLoop forLoop = new ForLoop(); + + public final Method method = new Method(); + + public final Variables variables = new Variables(); + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/CatchClause.java b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/CatchClause.java new file mode 100644 index 000000000..1f98b7d26 --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/CatchClause.java @@ -0,0 +1,14 @@ +package com.helger.jcodemodel.writer.settings.wrap; + +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; + +public class CatchClause { + + /// declaration of the catch types + public final ListWrapping types = + new ListWrapping() + .condition(EListWrapStrategy.NEVER) + .indent(1); + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/ForLoop.java b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/ForLoop.java new file mode 100644 index 000000000..c4e33486c --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/ForLoop.java @@ -0,0 +1,14 @@ +package com.helger.jcodemodel.writer.settings.wrap; + +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; + +public class ForLoop { + + /// declaration of the loop init + public final ListWrapping init = + new ListWrapping() + .condition(EListWrapStrategy.NEVER) + .indent(1); + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/Method.java b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/Method.java new file mode 100644 index 000000000..5cd16372b --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/Method.java @@ -0,0 +1,40 @@ +package com.helger.jcodemodel.writer.settings.wrap; + +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping; +import com.helger.jcodemodel.writer.settings.Wrap.WordWrapping; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; +import com.helger.jcodemodel.writer.settings.Wrap.WordWrapping.EWordWrapStrategy; + +public class Method { + + /// wrapping of the method's return type + public final WordWrapping type = + new WordWrapping() + .condition(EWordWrapStrategy.NEVER) + .indent(1); + + /// wrapping of the method's name when declaring it + public final WordWrapping name = + new WordWrapping() + .condition(EWordWrapStrategy.NEVER) + .indent(1); + + /// declaration of the method's params + public final ListWrapping params = + new ListWrapping() + .condition(EListWrapStrategy.PAST3) + .indent(1); + + /// wrapping of opening bracket ( '{' ) when declaring + public final WordWrapping bracket = + new WordWrapping() + .condition(EWordWrapStrategy.NEVER) + .indent(0); + + /// wrapping of the arguments when calling the method + public final ListWrapping args = + new ListWrapping() + .condition(EListWrapStrategy.PAST3) + .indent(1); + +} diff --git a/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/Variables.java b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/Variables.java new file mode 100644 index 000000000..53daa92c6 --- /dev/null +++ b/jcodemodel/src/main/java/com/helger/jcodemodel/writer/settings/wrap/Variables.java @@ -0,0 +1,26 @@ +package com.helger.jcodemodel.writer.settings.wrap; + +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; + +public class Variables { + + /// array init for array variable + public final ListWrapping array = + new ListWrapping() + .condition(EListWrapStrategy.REQUIRED) + .indent(1); + + /// declaration of variable inside a block + public final ListWrapping block = + new ListWrapping() + .condition(EListWrapStrategy.REQUIRED) + .indent(1); + + /// declaration a class' field + public final ListWrapping field = + new ListWrapping() + .condition(EListWrapStrategy.REQUIRED) + .indent(1); + +} diff --git a/jcodemodel/src/test/java/com/helger/jcodemodel/JAnnotatedClassTest.java b/jcodemodel/src/test/java/com/helger/jcodemodel/JAnnotatedClassTest.java index 4e05f1617..edb568fc3 100644 --- a/jcodemodel/src/test/java/com/helger/jcodemodel/JAnnotatedClassTest.java +++ b/jcodemodel/src/test/java/com/helger/jcodemodel/JAnnotatedClassTest.java @@ -278,7 +278,7 @@ public void testAnnotatedMethodParameter () throws JCodeModelException // Check the generated output contains the annotated type in parameter final String classOutput = CodeModelTestsHelper.declare (testClass); - assertTrue ("Expected java.util.List<@java.lang.Deprecated java.lang.String> in method parameter", + assertTrue ("Expected java.util.List<@java.lang.Deprecated java.lang.String> in method parameter ; got "+classOutput, classOutput.contains ("java.util.List<@java.lang.Deprecated java.lang.String> items")); // Verify it parses diff --git a/jcodemodel/src/test/java/com/helger/jcodemodel/util/CodeModelTestsHelper.java b/jcodemodel/src/test/java/com/helger/jcodemodel/util/CodeModelTestsHelper.java index c4445a148..59ee94824 100644 --- a/jcodemodel/src/test/java/com/helger/jcodemodel/util/CodeModelTestsHelper.java +++ b/jcodemodel/src/test/java/com/helger/jcodemodel/util/CodeModelTestsHelper.java @@ -78,6 +78,7 @@ import com.helger.jcodemodel.compile.DynamicClassLoader; import com.helger.jcodemodel.compile.MemoryCodeWriter; import com.helger.jcodemodel.writer.AbstractCodeWriter; +import com.helger.jcodemodel.writer.FormatterSettings; import com.helger.jcodemodel.writer.JCMWriter; import com.helger.jcodemodel.writer.JFormatter; import com.helger.jcodemodel.writer.OutputStreamCodeWriter; @@ -99,7 +100,7 @@ public final class CodeModelTestsHelper private static IJFormatter _createFormatter (@NonNull final NonBlockingStringWriter aWriter) { return new JFormatter (new SourcePrintWriter (aWriter, JCMWriter.DEFAULT_NEW_LINE), - JCMWriter.DEFAULT_INDENT_STRING); + new FormatterSettings()); } /** Hidden constructor. */ @@ -269,15 +270,18 @@ private static CompilationUnit _parseWithJavaParser (final String sUnitName, fin final IProgressMonitor aPM = null; final org.eclipse.jdt.core.dom.CompilationUnit astRoot = (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST (aPM); - if (astRoot == null) + if (astRoot == null) { throw new IllegalStateException ("Failed to compile:\n" + new String (aCode)); + } - if (false) + if (false) { LOGGER.info (astRoot.toString ()); + } final IProblem [] aProblems = astRoot.getProblems (); - if (aProblems != null && aProblems.length > 0) + if (aProblems != null && aProblems.length > 0) { throw new IllegalStateException ("Compilation problems " + Arrays.toString (aProblems)); + } return astRoot; } diff --git a/jcodemodel/src/test/java/com/helger/jcodemodel/writer/JFormatterTest.java b/jcodemodel/src/test/java/com/helger/jcodemodel/writer/JFormatterTest.java new file mode 100644 index 000000000..85e765f0b --- /dev/null +++ b/jcodemodel/src/test/java/com/helger/jcodemodel/writer/JFormatterTest.java @@ -0,0 +1,129 @@ +package com.helger.jcodemodel.writer; + +import org.junit.Assert; +import org.junit.Test; + +import com.helger.jcodemodel.util.NullWriter; +import com.helger.jcodemodel.writer.JFormatter.FormatterContext; +import com.helger.jcodemodel.writer.JFormatter.WriteContext; + +public class JFormatterTest { + + @Test + public void testSizeWithTabsExpanded() { + Assert.assertEquals(2, JFormatter.sizeWithTabsExpanded("\t", 2)); + Assert.assertEquals(4, JFormatter.sizeWithTabsExpanded("\t", 4)); + Assert.assertEquals(4, JFormatter.sizeWithTabsExpanded("a\t", 4)); + Assert.assertEquals(4, JFormatter.sizeWithTabsExpanded("ab\t", 4)); + Assert.assertEquals(4, JFormatter.sizeWithTabsExpanded("abc\t", 4)); + Assert.assertEquals(8, JFormatter.sizeWithTabsExpanded("abcd\t", 4)); + Assert.assertEquals(8, JFormatter.sizeWithTabsExpanded("abcde\t", 4)); + Assert.assertEquals(8, JFormatter.sizeWithTabsExpanded("abcdef\t", 4)); + Assert.assertEquals(8, JFormatter.sizeWithTabsExpanded("abcdefg\t", 4)); + Assert.assertEquals(12, JFormatter.sizeWithTabsExpanded("abcdefgh\t", 4)); + Assert.assertEquals(8, JFormatter.sizeWithTabsExpanded("\t\t", 4)); + Assert.assertEquals(8, JFormatter.sizeWithTabsExpanded("\tab\t", 4)); + } + + @Test + public void testContexts() { + FormatterSettings settings = new FormatterSettings(); + settings.indent.useSpaces(1); + try (JFormatter test = + new JFormatter(new SourcePrintWriter(NullWriter.getInstance(), JCMWriter.DEFAULT_NEW_LINE), settings);) { + WriteContext root = test.asContext; + + Assert.assertEquals(0, test.indentLevel()); + Assert.assertEquals(0, root.getIndentLevel()); + Assert.assertEquals("", root.getCurrentLine()); + Assert.assertEquals(0, root.getLastChar()); + + test.print("test"); + Assert.assertEquals(0, test.indentLevel()); + Assert.assertEquals(0, root.getIndentLevel()); + Assert.assertEquals("test", root.getCurrentLine()); + Assert.assertEquals('t', root.getLastChar()); + + test.indent(2); + Assert.assertEquals(2, test.indentLevel()); + Assert.assertEquals(2, root.getIndentLevel()); + Assert.assertEquals("test", root.getCurrentLine()); + Assert.assertEquals('t', root.getLastChar()); + + test.newline(); + Assert.assertEquals(2, test.indentLevel()); + Assert.assertEquals(2, root.getIndentLevel()); + Assert.assertEquals("", root.getCurrentLine()); + Assert.assertEquals(0, root.getLastChar()); + + test.print('o'); + Assert.assertEquals(2, test.indentLevel()); + Assert.assertEquals(2, root.getIndentLevel()); + Assert.assertEquals(" o", root.getCurrentLine()); + Assert.assertEquals('o', root.getLastChar()); + + test.outdent(1); + Assert.assertEquals(1, test.indentLevel()); + Assert.assertEquals(1, root.getIndentLevel()); + Assert.assertEquals(" o", root.getCurrentLine()); + Assert.assertEquals('o', root.getLastChar()); + + test.newline(); + Assert.assertEquals(1, test.indentLevel()); + Assert.assertEquals(1, root.getIndentLevel()); + Assert.assertEquals("", root.getCurrentLine()); + Assert.assertEquals(0, root.getLastChar()); + + test.print("sterone"); + Assert.assertEquals(1, test.indentLevel()); + Assert.assertEquals(1, root.getIndentLevel()); + Assert.assertEquals(" sterone", root.getCurrentLine()); + Assert.assertEquals('e', root.getLastChar()); + + FormatterContext layer = (FormatterContext) test.addContextLayer(); + Assert.assertEquals(1, test.indentLevel()); + Assert.assertEquals(1, root.getIndentLevel()); + Assert.assertEquals(" sterone", root.getCurrentLine()); + Assert.assertEquals('e', root.getLastChar()); + Assert.assertEquals(1, layer.getIndentLevel()); + Assert.assertEquals(" sterone", layer.getCurrentLine()); + Assert.assertEquals('e', layer.getLastChar()); + + test.indent(2); + Assert.assertEquals(3, test.indentLevel()); + Assert.assertEquals(1, root.getIndentLevel()); + Assert.assertEquals(" sterone", root.getCurrentLine()); + Assert.assertEquals('e', root.getLastChar()); + Assert.assertEquals(3, layer.getIndentLevel()); + Assert.assertEquals(" sterone", layer.getCurrentLine()); + Assert.assertEquals('e', layer.getLastChar()); + + test.newline(); + Assert.assertEquals(3, test.indentLevel()); + Assert.assertEquals(1, root.getIndentLevel()); + Assert.assertEquals(" sterone", root.getCurrentLine()); + Assert.assertEquals('e', root.getLastChar()); + Assert.assertEquals(3, layer.getIndentLevel()); + Assert.assertEquals("", layer.getCurrentLine()); + Assert.assertEquals(0, layer.getLastChar()); + + test.print("oid"); + Assert.assertEquals(3, test.indentLevel()); + Assert.assertEquals(1, root.getIndentLevel()); + Assert.assertEquals(" sterone", root.getCurrentLine()); + Assert.assertEquals('e', root.getLastChar()); + Assert.assertEquals(3, layer.getIndentLevel()); + Assert.assertEquals(" oid", layer.getCurrentLine()); + Assert.assertEquals('d', layer.getLastChar()); + + layer.commit(); + Assert.assertEquals(3, test.indentLevel()); + Assert.assertEquals(3, root.getIndentLevel()); + Assert.assertEquals(" oid", root.getCurrentLine()); + Assert.assertEquals('d', root.getLastChar()); + + } + + } + +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/arrayinit/ArrayInitSimpleClass.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/arrayinit/ArrayInitSimpleClass.java new file mode 100644 index 000000000..415741706 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/arrayinit/ArrayInitSimpleClass.java @@ -0,0 +1,27 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.arrayinit; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class ArrayInitSimpleClass { + public static final int[] i = { 0, 1, 2, 3, 4, 5 }; + public static final int[] i0 = {}; + public static final char[] c = {'a'}; + public static final double[] d = { 0.0, 0.1, 0.2, 0.3 }; + public static final String[] s = {null, "s", "sss"}; + public static final Object[] o = {i, i0, c, d, s }; +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/DefaultWrapOptions.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/DefaultWrapOptions.java new file mode 100644 index 000000000..b55ae2f23 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/DefaultWrapOptions.java @@ -0,0 +1,31 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.catchclause; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class DefaultWrapOptions { + + public static final void multiplecatch() { + try { + } catch (ClassCastException ex) { + } catch (ArithmeticException exception1) { + } catch (ArrayIndexOutOfBoundsException | ArrayStoreException | BufferOverflowException | BufferUnderflowException ex) { + } + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/DisabledWrap.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/DisabledWrap.java new file mode 100644 index 000000000..07cf5cb34 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/DisabledWrap.java @@ -0,0 +1,31 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.catchclause; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class DisabledWrap { + + public static final void multiplecatch() { + try { + } catch (ClassCastException ex) { + } catch (ArithmeticException exception1) { + } catch (ArrayIndexOutOfBoundsException | ArrayStoreException | BufferOverflowException | BufferUnderflowException ex) { + } + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/WrapTypesBinary.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/WrapTypesBinary.java new file mode 100644 index 000000000..e50242c82 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/WrapTypesBinary.java @@ -0,0 +1,35 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.catchclause; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapTypesBinary { + + public static final void multiplecatch() { + try { + } catch (ClassCastException ex) { + } catch (ArithmeticException exception1) { + } catch ( + ArrayIndexOutOfBoundsException | + ArrayStoreException | + BufferOverflowException | + BufferUnderflowException ex) { + } + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/WrapTypesRequired.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/WrapTypesRequired.java new file mode 100644 index 000000000..edb5a4bec --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/catchclause/WrapTypesRequired.java @@ -0,0 +1,32 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.catchclause; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapTypesRequired { + + public static final void multiplecatch() { + try { + } catch (ClassCastException ex) { + } catch (ArithmeticException exception1) { + } catch (ArrayIndexOutOfBoundsException | ArrayStoreException | + BufferOverflowException | BufferUnderflowException ex) { + } + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/DefaultWrapOptions.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/DefaultWrapOptions.java new file mode 100644 index 000000000..942e43124 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/DefaultWrapOptions.java @@ -0,0 +1,30 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.forloop; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class DefaultWrapOptions { + + public static final void initExpressions() { + int i; + for (i = 0, i = 1, i = 2, i = 3, i = 4, i = 5, i = 6, i = 7, i = 8, i = 9; ; ); + } + + public static final void initVariables() { + for (int init0 = 0, init1 [] = null, init2 [][] = null, init3 [][][] = null, init4 [][][][] = null, init5 [][][][][] = null, init6 [][][][][][] = null, init7 [][][][][][][] = null, init8 [][][][][][][][] = null, init9 [][][][][][][][][] = null; ; ); + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/DisabledWrap.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/DisabledWrap.java new file mode 100644 index 000000000..f22206ff5 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/DisabledWrap.java @@ -0,0 +1,30 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.forloop; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class DisabledWrap { + + public static final void initExpressions() { + int i; + for (i = 0, i = 1, i = 2, i = 3, i = 4, i = 5, i = 6, i = 7, i = 8, i = 9; ; ); + } + + public static final void initVariables() { + for (int init0 = 0, init1 [] = null, init2 [][] = null, init3 [][][] = null, init4 [][][][] = null, init5 [][][][][] = null, init6 [][][][][][] = null, init7 [][][][][][][] = null, init8 [][][][][][][][] = null, init9 [][][][][][][][][] = null; ; ); + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/WrapInitBinary.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/WrapInitBinary.java new file mode 100644 index 000000000..735da4bfb --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/WrapInitBinary.java @@ -0,0 +1,50 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.forloop; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapInitBinary { + + public static final void initExpressions() { + int i; + for ( + i = 0, + i = 1, + i = 2, + i = 3, + i = 4, + i = 5, + i = 6, + i = 7, + i = 8, + i = 9; ; ); + } + + public static final void initVariables() { + for ( + int init0 = 0, + init1 [] = null, + init2 [][] = null, + init3 [][][] = null, + init4 [][][][] = null, + init5 [][][][][] = null, + init6 [][][][][][] = null, + init7 [][][][][][][] = null, + init8 [][][][][][][][] = null, + init9 [][][][][][][][][] = null; ; ); + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/WrapInitRequired.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/WrapInitRequired.java new file mode 100644 index 000000000..4db249750 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/forloop/WrapInitRequired.java @@ -0,0 +1,34 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.forloop; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapInitRequired { + + public static final void initExpressions() { + int i; + for (i = 0, i = 1, i = 2, i = 3, i = 4, i = 5, i = 6, i = 7, i = 8, + i = 9; ; ); + } + + public static final void initVariables() { + for (int init0 = 0, init1 [] = null, init2 [][] = null, + init3 [][][] = null, init4 [][][][] = null, init5 [][][][][] = null, + init6 [][][][][][] = null, init7 [][][][][][][] = null, + init8 [][][][][][][][] = null, init9 [][][][][][][][][] = null; ; ); + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/DefaultWrapOptions.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/DefaultWrapOptions.java new file mode 100644 index 000000000..c64c4a693 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/DefaultWrapOptions.java @@ -0,0 +1,45 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class DefaultWrapOptions { + + public static void artificiallyVeryLongMethodNameWith2Args(int i1, int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args(int i1, + int i2, + int i3, + int i4, + int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs(int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs(int i1, int i2, int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs(int i1, + int i2, + int i3, + int i4, + int i5, + int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/DisabledWrap.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/DisabledWrap.java new file mode 100644 index 000000000..cc5a6db57 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/DisabledWrap.java @@ -0,0 +1,45 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class DisabledWrap { + + public static void artificiallyVeryLongMethodNameWith2Args(int i1, int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args(int i1, + int i2, + int i3, + int i4, + int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs(int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs(int i1, int i2, int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs(int i1, + int i2, + int i3, + int i4, + int i5, + int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapBracketAlways.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapBracketAlways.java new file mode 100644 index 000000000..9fc4a86e7 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapBracketAlways.java @@ -0,0 +1,50 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapBracketAlways { + + public static void artificiallyVeryLongMethodNameWith2Args(int i1, int i2) + { + } + + public static void artificiallyVeryLongMethodNameWith5Args(int i1, + int i2, + int i3, + int i4, + int i5) + { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs(int... ints) + { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs(int i1, int i2, int... ints) + { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs(int i1, + int i2, + int i3, + int i4, + int i5, + int... ints) + { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapBracketNever.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapBracketNever.java new file mode 100644 index 000000000..3d1b1a8ff --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapBracketNever.java @@ -0,0 +1,45 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapBracketNever { + + public static void artificiallyVeryLongMethodNameWith2Args(int i1, int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args(int i1, + int i2, + int i3, + int i4, + int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs(int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs(int i1, int i2, int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs(int i1, + int i2, + int i3, + int i4, + int i5, + int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapBracketRequired.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapBracketRequired.java new file mode 100644 index 000000000..7d766828d --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapBracketRequired.java @@ -0,0 +1,46 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapBracketRequired { + + public static void artificiallyVeryLongMethodNameWith2Args(int i1, int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args(int i1, + int i2, + int i3, + int i4, + int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs(int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs(int i1, int i2, int... ints) + { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs(int i1, + int i2, + int i3, + int i4, + int i5, + int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapNameAlwaysI3.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapNameAlwaysI3.java new file mode 100644 index 000000000..03f2d2768 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapNameAlwaysI3.java @@ -0,0 +1,50 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapNameAlwaysI3 { + + public static void + artificiallyVeryLongMethodNameWith2Args(int i1, int i2) { + } + + public static void + artificiallyVeryLongMethodNameWith5Args(int i1, + int i2, + int i3, + int i4, + int i5) { + } + + public static void + artificiallyVeryLongMethodNameWithVarArgs(int... ints) { + } + + public static void + artificiallyVeryLongMethodNameWith2ArgsAndVarArgs(int i1, int i2, int... ints) { + } + + public static void + artificiallyVeryLongMethodNameWith5ArgsAndVarArgs(int i1, + int i2, + int i3, + int i4, + int i5, + int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapNameNever.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapNameNever.java new file mode 100644 index 000000000..508a7df69 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapNameNever.java @@ -0,0 +1,45 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapNameNever { + + public static void artificiallyVeryLongMethodNameWith2Args(int i1, int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args(int i1, + int i2, + int i3, + int i4, + int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs(int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs(int i1, int i2, int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs(int i1, + int i2, + int i3, + int i4, + int i5, + int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapNameRequiredI1W70.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapNameRequiredI1W70.java new file mode 100644 index 000000000..dfc176ab0 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapNameRequiredI1W70.java @@ -0,0 +1,47 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapNameRequiredI1W70 { + + public static void artificiallyVeryLongMethodNameWith2Args(int i1, int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args(int i1, + int i2, + int i3, + int i4, + int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs(int... ints) { + } + + public static void + artificiallyVeryLongMethodNameWith2ArgsAndVarArgs(int i1, int i2, int... ints) { + } + + public static void + artificiallyVeryLongMethodNameWith5ArgsAndVarArgs(int i1, + int i2, + int i3, + int i4, + int i5, + int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsAlways.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsAlways.java new file mode 100644 index 000000000..a7e3c87c4 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsAlways.java @@ -0,0 +1,53 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapParamsAlways { + + public static void artificiallyVeryLongMethodNameWith2Args( + int i1, + int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args( + int i1, + int i2, + int i3, + int i4, + int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs( + int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs( + int i1, + int i2, + int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs( + int i1, + int i2, + int i3, + int i4, + int i5, + int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsAlwaysBeforeSep.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsAlwaysBeforeSep.java new file mode 100644 index 000000000..3aced7e5e --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsAlwaysBeforeSep.java @@ -0,0 +1,53 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapParamsAlwaysBeforeSep { + + public static void artificiallyVeryLongMethodNameWith2Args( + int i1 + , int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args( + int i1 + , int i2 + , int i3 + , int i4 + , int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs( + int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs( + int i1 + , int i2 + , int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs( + int i1 + , int i2 + , int i3 + , int i4 + , int i5 + , int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsBinaryI2.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsBinaryI2.java new file mode 100644 index 000000000..c0d84d53e --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsBinaryI2.java @@ -0,0 +1,50 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapParamsBinaryI2 { + + public static void artificiallyVeryLongMethodNameWith2Args(int i1, int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args( + int i1, + int i2, + int i3, + int i4, + int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs(int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs( + int i1, + int i2, + int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs( + int i1, + int i2, + int i3, + int i4, + int i5, + int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsBinaryI2W50.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsBinaryI2W50.java new file mode 100644 index 000000000..eb8cbbfbd --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsBinaryI2W50.java @@ -0,0 +1,53 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapParamsBinaryI2W50 { + + public static void artificiallyVeryLongMethodNameWith2Args( + int i1, + int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args( + int i1, + int i2, + int i3, + int i4, + int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs( + int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs( + int i1, + int i2, + int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs( + int i1, + int i2, + int i3, + int i4, + int i5, + int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsNever.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsNever.java new file mode 100644 index 000000000..c16e1517d --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsNever.java @@ -0,0 +1,36 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapParamsNever { + + public static void artificiallyVeryLongMethodNameWith2Args(int i1, int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args(int i1, int i2, int i3, int i4, int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs(int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs(int i1, int i2, int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs(int i1, int i2, int i3, int i4, int i5, int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsRequired.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsRequired.java new file mode 100644 index 000000000..2da8d7864 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/method/WrapParamsRequired.java @@ -0,0 +1,39 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.method; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapParamsRequired { + + public static void artificiallyVeryLongMethodNameWith2Args(int i1, int i2) { + } + + public static void artificiallyVeryLongMethodNameWith5Args(int i1, int i2, + int i3, int i4, int i5) { + } + + public static void artificiallyVeryLongMethodNameWithVarArgs(int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith2ArgsAndVarArgs(int i1, + int i2, int... ints) { + } + + public static void artificiallyVeryLongMethodNameWith5ArgsAndVarArgs(int i1, + int i2, int i3, int i4, int i5, int... ints) { + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/DefaultArrayInitWrapOptions.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/DefaultArrayInitWrapOptions.java new file mode 100644 index 000000000..782c5e3c3 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/DefaultArrayInitWrapOptions.java @@ -0,0 +1,25 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.variables.arrayinit; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class DefaultArrayInitWrapOptions { + public static final char[] empty = {}; + public static final int[] many = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20 }; + public static final int[] few = { 0, 1, 2, 3, 4 }; +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitAlways.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitAlways.java new file mode 100644 index 000000000..97cb36e13 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitAlways.java @@ -0,0 +1,50 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.variables.arrayinit; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapArrayInitAlways { + public static final char[] empty = {}; + public static final int[] many = { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20 }; + public static final int[] few = { + 0, + 1, + 2, + 3, + 4 }; +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitBinary.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitBinary.java new file mode 100644 index 000000000..66d5132ae --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitBinary.java @@ -0,0 +1,45 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.variables.arrayinit; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapArrayInitBinary { + public static final char[] empty = {}; + public static final int[] many = { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20 }; + public static final int[] few = { 0, 1, 2, 3, 4 }; +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitNever.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitNever.java new file mode 100644 index 000000000..e09095e9f --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitNever.java @@ -0,0 +1,24 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.variables.arrayinit; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapArrayInitNever { + public static final char[] empty = {}; + public static final int[] many = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; + public static final int[] few = { 0, 1, 2, 3, 4 }; +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitRequired.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitRequired.java new file mode 100644 index 000000000..05ce0ee48 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/arrayinit/WrapArrayInitRequired.java @@ -0,0 +1,25 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.variables.arrayinit; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapArrayInitRequired { + public static final char[] empty = {}; + public static final int[] many = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20 }; + public static final int[] few = { 0, 1, 2, 3, 4 }; +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/block/DefaultWrapOptions.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/block/DefaultWrapOptions.java new file mode 100644 index 000000000..d8c76dc14 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/block/DefaultWrapOptions.java @@ -0,0 +1,30 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.variables.block; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class DefaultWrapOptions { + + public static void test() { + char a; + char[] b = {'b', 'b'}, c[] = {{}}, variable_d = {'d'}, + variable_e = {'e'}, variable_f = {'f'}, variable_g = {'g'}, + variable_h = {'h'}, variable_i = {'i'}, variable_j = {'j'}, + variable_k = {'k'}; + String[] s = {null, null }; + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/block/WrapBlockBinary.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/block/WrapBlockBinary.java new file mode 100644 index 000000000..9c8276029 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/block/WrapBlockBinary.java @@ -0,0 +1,36 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.variables.block; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapBlockBinary { + + public static void test() { + char a; + char[] b = {'b', 'b'}, + c[] = {{}}, + variable_d = {'d'}, + variable_e = {'e'}, + variable_f = {'f'}, + variable_g = {'g'}, + variable_h = {'h'}, + variable_i = {'i'}, + variable_j = {'j'}, + variable_k = {'k'}; + String[] s = {null, null }; + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/block/WrapBlockRequired.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/block/WrapBlockRequired.java new file mode 100644 index 000000000..a04ee23e7 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/block/WrapBlockRequired.java @@ -0,0 +1,30 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.variables.block; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapBlockRequired { + + public static void test() { + char a; + char[] b = {'b', 'b'}, c[] = {{}}, variable_d = {'d'}, + variable_e = {'e'}, variable_f = {'f'}, variable_g = {'g'}, + variable_h = {'h'}, variable_i = {'i'}, variable_j = {'j'}, + variable_k = {'k'}; + String[] s = {null, null }; + } +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/field/DefaultWrapOptions.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/field/DefaultWrapOptions.java new file mode 100644 index 000000000..aff800ccc --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/field/DefaultWrapOptions.java @@ -0,0 +1,26 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.variables.field; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class DefaultWrapOptions { + public static final char[] a = null; + public static final char[] b = {'b'}, c[] = null, variable_2 = null, + variable_3 = null, variable_4 = null, variable_5 = null, + variable_6 = null, variable_7 = null, variable_8 = null, + variable_9 = null; +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/field/WrapFieldBinary.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/field/WrapFieldBinary.java new file mode 100644 index 000000000..4840c320b --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/field/WrapFieldBinary.java @@ -0,0 +1,32 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.variables.field; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapFieldBinary { + public static final char[] a = null; + public static final char[] b = {'b'}, + c[] = null, + variable_2 = null, + variable_3 = null, + variable_4 = null, + variable_5 = null, + variable_6 = null, + variable_7 = null, + variable_8 = null, + variable_9 = null; +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/field/WrapFieldRequired.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/field/WrapFieldRequired.java new file mode 100644 index 000000000..bdc533c6e --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/format/variables/field/WrapFieldRequired.java @@ -0,0 +1,26 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.format.variables.field; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class WrapFieldRequired { + public static final char[] a = null; + public static final char[] b = {'b'}, c[] = null, variable_2 = null, + variable_3 = null, variable_4 = null, variable_5 = null, + variable_6 = null, variable_7 = null, variable_8 = null, + variable_9 = null; +} diff --git a/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/samevars/SameVarsSimpleClass.java b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/samevars/SameVarsSimpleClass.java new file mode 100644 index 000000000..cc575b878 --- /dev/null +++ b/jcodemodeltests/src/generated/javatest/com/helger/jcodemodel/tests/samevars/SameVarsSimpleClass.java @@ -0,0 +1,27 @@ +/** + * 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. + * + */ +package com.helger.jcodemodel.tests.samevars; + +import javax.annotation.processing.Generated; + +@Generated("com.helger.jcodemodel.JCodeModel") +public class SameVarsSimpleClass { + public static int i = 3, j, k = 1; + public static char[] a1, a2, a3 []; + + public static void test() { + int i = 11, j, k = 5; + } +} diff --git a/jcodemodeltests/src/main/java/com/helger/jcodemodel/compile/annotation/GenerateTestFiles.java b/jcodemodeltests/src/main/java/com/helger/jcodemodel/compile/annotation/GenerateTestFiles.java index d2bdcb31b..e152f39ab 100644 --- a/jcodemodeltests/src/main/java/com/helger/jcodemodel/compile/annotation/GenerateTestFiles.java +++ b/jcodemodeltests/src/main/java/com/helger/jcodemodel/compile/annotation/GenerateTestFiles.java @@ -29,6 +29,7 @@ import com.helger.jcodemodel.JCodeModel; import com.helger.jcodemodel.JPackage; import com.helger.jcodemodel.JReferencedClass; +import com.helger.jcodemodel.writer.FormatterSettings; import com.helger.jcodemodel.writer.JCMWriter; import com.helger.jcodemodel.writer.ProgressCodeWriter.IProgressTracker; @@ -70,8 +71,9 @@ public static void main (final String [] args) public static int extractJavaFeature () { final String sValue = System.getProperty ("java.feature"); - if (sValue == null || sValue.isBlank ()) + if (sValue == null || sValue.isBlank ()) { return JCMWriter.DEFAULT_JAVA_FEATURE; + } try { // accept full version strings like "17.0.5" by taking the major component @@ -86,9 +88,9 @@ public static int extractJavaFeature () public GenerateTestFiles (final File outputDir, final File classScanDir) { - this.m_aOutputDir = outputDir; - this.m_aClassScanDir = classScanDir; - this.m_nJavaFeature = extractJavaFeature (); + m_aOutputDir = outputDir; + m_aClassScanDir = classScanDir; + m_nJavaFeature = extractJavaFeature (); } void apply () @@ -181,6 +183,7 @@ private void runGeneration (final Class clazz) throws IllegalAccessException boolean missingParam = false; JCodeModel produced = null; JPackage rootPackage = null; + FormatterSettings settings = null; for (int i = 0; i < params.length; i++) { final Parameter param = m.getParameters ()[i]; @@ -208,6 +211,11 @@ private void runGeneration (final Class clazz) throws IllegalAccessException params[i] = rootPackage; requiresJCM = true; + } else if (param.getType() == FormatterSettings.class) { + if (settings == null) { + settings = new FormatterSettings(); + } + params[i] = settings; } else { @@ -243,7 +251,10 @@ private void runGeneration (final Class clazz) throws IllegalAccessException if (produced != null) { postProcessJCM (produced); - new JCMWriter (produced).setJavaFeature (m_nJavaFeature).build (m_aOutputDir, (IProgressTracker) null); + new JCMWriter(produced) + .withSettings(settings) + .setJavaFeature(m_nJavaFeature) + .build(m_aOutputDir, (IProgressTracker) null); } } } diff --git a/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/arrayinit/ArrayInitTestGen.java b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/arrayinit/ArrayInitTestGen.java new file mode 100644 index 000000000..bceef4398 --- /dev/null +++ b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/arrayinit/ArrayInitTestGen.java @@ -0,0 +1,30 @@ +package com.helger.jcodemodel.tests.arrayinit; + +import com.helger.jcodemodel.JDefinedClass; +import com.helger.jcodemodel.JExpr; +import com.helger.jcodemodel.JFieldVar; +import com.helger.jcodemodel.JMod; +import com.helger.jcodemodel.JPackage; +import com.helger.jcodemodel.compile.annotation.TestJCM; +import com.helger.jcodemodel.exceptions.JCodeModelException; + +@TestJCM + +public class ArrayInitTestGen { + + public void simpleClass(final JPackage root) throws JCodeModelException { + final JDefinedClass cl = root._class("ArrayInitSimpleClass"); + + JFieldVar i = cl.field(JMod.PUBLIC_STATIC_FINAL, cl.owner().INT.array(), "i", JExpr.arrayInit(0, 1, 2, 3, 4, 5)); + JFieldVar i0 = cl.field(JMod.PUBLIC_STATIC_FINAL, cl.owner().INT.array(), "i0", JExpr.arrayInit()); + JFieldVar c = cl.field(JMod.PUBLIC_STATIC_FINAL, cl.owner().CHAR.array(), "c", JExpr.arrayInit('a')); + JFieldVar d = cl.field(JMod.PUBLIC_STATIC_FINAL, cl.owner().DOUBLE.array(), "d", JExpr.arrayInit(.0, .1, .2, .3)); + JFieldVar s = + cl.field(JMod.PUBLIC_STATIC_FINAL, cl.owner().ref(String.class).array(), "s", + JExpr.arrayInit(null, JExpr.lit("s"), JExpr.lit("sss"))); + cl.field(JMod.PUBLIC_STATIC_FINAL, cl.owner().ref(Object.class).array(), "o", + JExpr.arrayInit(i, i0, c, d, s)); + + } + +} diff --git a/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/catchclause/CatchClauseTestGen.java b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/catchclause/CatchClauseTestGen.java new file mode 100644 index 000000000..080ea6061 --- /dev/null +++ b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/catchclause/CatchClauseTestGen.java @@ -0,0 +1,57 @@ +package com.helger.jcodemodel.tests.format.catchclause; + +import java.nio.BufferOverflowException; +import java.nio.BufferUnderflowException; + +import com.helger.jcodemodel.JDefinedClass; +import com.helger.jcodemodel.JMethod; +import com.helger.jcodemodel.JMod; +import com.helger.jcodemodel.JPackage; +import com.helger.jcodemodel.JTryBlock; +import com.helger.jcodemodel.compile.annotation.TestJCM; +import com.helger.jcodemodel.exceptions.JCodeModelException; +import com.helger.jcodemodel.writer.FormatterSettings; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; + +@TestJCM +public class CatchClauseTestGen { + + public static void addCatchMethod(JDefinedClass jdc) { + { + JMethod m = jdc.method(JMod.PUBLIC_STATIC_FINAL, jdc.owner().VOID, "multiplecatch"); + JTryBlock tr = m.body()._try(); + // we just iterate over a lot of various children of RuntimeException in the + // base java packages + tr._catch(jdc.owner().ref(ClassCastException.class)); + tr._catch(jdc.owner().ref(ArithmeticException.class), "exception1"); + tr._catch(jdc.owner().ref(ArrayIndexOutOfBoundsException.class)).param() + .addType(jdc.owner().ref(ArrayStoreException.class)) + .addType(jdc.owner().ref(BufferOverflowException.class)) + .addType(jdc.owner().ref(BufferUnderflowException.class)); + } + } + + protected static void addClassMethod(JPackage root, String className) throws JCodeModelException { + addCatchMethod(root._class(className)); + } + + public void testWithDisabled(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.disable(); + addClassMethod(root, "DisabledWrap"); + } + + public void testWithDefaultOptions(final JPackage root) throws JCodeModelException { + addClassMethod(root, "DefaultWrapOptions"); + } + + public void testWithWrapTypesBinary(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.catchClause.types.condition(EListWrapStrategy.BINARY); + addClassMethod(root, "WrapTypesBinary"); + } + + public void testWithWrapTypesRequired(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.catchClause.types.condition(EListWrapStrategy.REQUIRED); + addClassMethod(root, "WrapTypesRequired"); + } + +} diff --git a/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/forloop/ForLoopTestGen.java b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/forloop/ForLoopTestGen.java new file mode 100644 index 000000000..2fda8a600 --- /dev/null +++ b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/forloop/ForLoopTestGen.java @@ -0,0 +1,62 @@ +package com.helger.jcodemodel.tests.format.forloop; + +import com.helger.jcodemodel.JDefinedClass; +import com.helger.jcodemodel.JExpr; +import com.helger.jcodemodel.JForLoop; +import com.helger.jcodemodel.JMethod; +import com.helger.jcodemodel.JMod; +import com.helger.jcodemodel.JPackage; +import com.helger.jcodemodel.compile.annotation.TestJCM; +import com.helger.jcodemodel.exceptions.JCodeModelException; +import com.helger.jcodemodel.vars.JBlockVar; +import com.helger.jcodemodel.writer.FormatterSettings; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; + +@TestJCM +public class ForLoopTestGen { + + public static void addForMethod(JDefinedClass jdc) { + // multiple blocks to avoid variables colliding + { + JMethod m = jdc.method(JMod.PUBLIC_STATIC_FINAL, jdc.owner().VOID, "initExpressions"); + JBlockVar vi = m.body().decl(jdc.owner().INT, "i"); + JForLoop _for = m.body()._for(); + for (int i = 0; i < 10; i++) { + _for.init(vi, JExpr.lit(i)); + } + } + + { + JMethod m = jdc.method(JMod.PUBLIC_STATIC_FINAL, jdc.owner().VOID, "initVariables"); + JForLoop _for = m.body()._for(); + JBlockVar initV = _for.init(jdc.owner().INT, "init0", JExpr.lit(0)); + for (int i = 1; i < 10; i++) { + initV.andVar("init" + i, i, JExpr._null()); + } + } + } + + protected static void addClassMethod(JPackage root, String className) throws JCodeModelException { + addForMethod(root._class(className)); + } + + public void testWithDisabled(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.disable(); + addClassMethod(root, "DisabledWrap"); + } + + public void testWithDefaultOptions(final JPackage root) throws JCodeModelException { + addClassMethod(root, "DefaultWrapOptions"); + } + + public void testWithWrapInitBinary(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.forLoop.init.condition(EListWrapStrategy.BINARY); + addClassMethod(root, "WrapInitBinary"); + } + + public void testWithWrapInitRequired(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.forLoop.init.condition(EListWrapStrategy.REQUIRED); + addClassMethod(root, "WrapInitRequired"); + } + +} diff --git a/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/method/MethodFormatTestGen.java b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/method/MethodFormatTestGen.java new file mode 100644 index 000000000..e30d23945 --- /dev/null +++ b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/method/MethodFormatTestGen.java @@ -0,0 +1,160 @@ +package com.helger.jcodemodel.tests.format.method; + +import com.helger.jcodemodel.JDefinedClass; +import com.helger.jcodemodel.JMethod; +import com.helger.jcodemodel.JMod; +import com.helger.jcodemodel.JPackage; +import com.helger.jcodemodel.compile.annotation.TestJCM; +import com.helger.jcodemodel.exceptions.JCodeModelException; +import com.helger.jcodemodel.writer.FormatterSettings; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; +import com.helger.jcodemodel.writer.settings.Wrap.WordWrapping.EWordWrapStrategy; + +@TestJCM +public class MethodFormatTestGen { + + protected static void addMethods(JDefinedClass clazz) { + JMethod meth = + clazz.method(JMod.PUBLIC | JMod.STATIC, clazz.owner().VOID, "artificiallyVeryLongMethodNameWith2Args"); + meth.param(clazz.owner().INT, "i1"); + meth.param(clazz.owner().INT, "i2"); + + meth = clazz.method(JMod.PUBLIC | JMod.STATIC, clazz.owner().VOID, "artificiallyVeryLongMethodNameWith5Args"); + meth.param(clazz.owner().INT, "i1"); + meth.param(clazz.owner().INT, "i2"); + meth.param(clazz.owner().INT, "i3"); + meth.param(clazz.owner().INT, "i4"); + meth.param(clazz.owner().INT, "i5"); + + meth = clazz.method(JMod.PUBLIC | JMod.STATIC, clazz.owner().VOID, "artificiallyVeryLongMethodNameWithVarArgs"); + meth.varParam(clazz.owner().INT, "ints"); + + meth = + clazz.method(JMod.PUBLIC | JMod.STATIC, clazz.owner().VOID, + "artificiallyVeryLongMethodNameWith2ArgsAndVarArgs"); + meth.param(clazz.owner().INT, "i1"); + meth.param(clazz.owner().INT, "i2"); + meth.varParam(clazz.owner().INT, "ints"); + + meth = + clazz.method(JMod.PUBLIC | JMod.STATIC, clazz.owner().VOID, + "artificiallyVeryLongMethodNameWith5ArgsAndVarArgs"); + meth.param(clazz.owner().INT, "i1"); + meth.param(clazz.owner().INT, "i2"); + meth.param(clazz.owner().INT, "i3"); + meth.param(clazz.owner().INT, "i4"); + meth.param(clazz.owner().INT, "i5"); + meth.varParam(clazz.owner().INT, "ints"); + } + + protected static void addClassMethod(JPackage root, String className) throws JCodeModelException { + addMethods(root._class(className)); + } + + // + // generic wrapping : default, disabled + // + + public void testWithDisabled(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.disable(); + addClassMethod(root, "DisabledWrap"); + } + + public void testWithDefaultOptions(final JPackage root) throws JCodeModelException { + addClassMethod(root, "DefaultWrapOptions"); + } + + // + // name + // + + public void testWithWrapNameAlwaysIndent3(final JPackage root, FormatterSettings settings) + throws JCodeModelException { + settings.wrap.method.name + .condition(EWordWrapStrategy.ALWAYS) + .indent(3); + addClassMethod(root, "WrapNameAlwaysI3"); + } + + public void testWithWrapNameNever(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.method.name.condition(EWordWrapStrategy.NEVER); + addClassMethod(root, "WrapNameNever"); + } + + public void testWithWrapNameRequiredIndent1Width70(final JPackage root, FormatterSettings settings) + throws JCodeModelException { + settings.wrap.method.name + .condition(EWordWrapStrategy.REQUIRED) + .indent(1); + settings.wrap.lineWidth = 70; + addClassMethod(root, "WrapNameRequiredI1W70"); + } + + // + // params + // + + public void testWithWrapParamsAlways(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.method.params.condition(EListWrapStrategy.ALWAYS); + addClassMethod(root, "WrapParamsAlways"); + } + + public void testWithWrapParamsAlwaysBeforeSep(final JPackage root, FormatterSettings settings) + throws JCodeModelException { + settings.wrap.method.params.condition(EListWrapStrategy.ALWAYS) + .wrapBeforeSep(); + addClassMethod(root, "WrapParamsAlwaysBeforeSep"); + } + + public void testWithWrapParamsNever(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.method.params.condition(EListWrapStrategy.NEVER); + addClassMethod(root, "WrapParamsNever"); + } + + public void testWithWrapParamsRequird(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.method.params.condition(EListWrapStrategy.REQUIRED); + addClassMethod(root, "WrapParamsRequired"); + } + + public void testWithParamsBinaryIndent2(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.method.params + .condition(EListWrapStrategy.BINARY) + .indent(2); + addClassMethod(root, "WrapParamsBinaryI2"); + } + + public void testWithParamsBinaryIndent2Width50(final JPackage root, FormatterSettings settings) + throws JCodeModelException { + settings.wrap.method.params + .condition(EListWrapStrategy.BINARY) + .indent(2); + settings.wrap.lineWidth(50); + addClassMethod(root, "WrapParamsBinaryI2W50"); + } + + // + // bracket + // + + public void testWithBracketWrapAlways(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.method.bracket + .condition(EWordWrapStrategy.ALWAYS) + .indent(0); + addClassMethod(root, "WrapBracketAlways"); + } + + public void testWithBracketWrapNever(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.method.bracket + .condition(EWordWrapStrategy.NEVER) + .indent(0); + addClassMethod(root, "WrapBracketNever"); + } + + public void testWithBracketWrapRequired(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.method.bracket + .condition(EWordWrapStrategy.REQUIRED) + .indent(0); + addClassMethod(root, "WrapBracketRequired"); + } + +} diff --git a/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/variables/arrayinit/ArrayInitFormatTestGen.java b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/variables/arrayinit/ArrayInitFormatTestGen.java new file mode 100644 index 000000000..eed27af3e --- /dev/null +++ b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/variables/arrayinit/ArrayInitFormatTestGen.java @@ -0,0 +1,55 @@ +package com.helger.jcodemodel.tests.format.variables.arrayinit; + +import com.helger.jcodemodel.JDefinedClass; +import com.helger.jcodemodel.JExpr; +import com.helger.jcodemodel.JMod; +import com.helger.jcodemodel.JPackage; +import com.helger.jcodemodel.compile.annotation.TestJCM; +import com.helger.jcodemodel.exceptions.JCodeModelException; +import com.helger.jcodemodel.writer.FormatterSettings; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; + +@TestJCM +public class ArrayInitFormatTestGen { + + protected static void addField(JDefinedClass clazz) { + + clazz.field(JMod.PUBLIC_STATIC_FINAL, clazz.owner().CHAR.array(), "empty", JExpr.arrayInit()); + clazz.field(JMod.PUBLIC_STATIC_FINAL, clazz.owner().INT.array(), "many", + JExpr.arrayInit(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)); + clazz.field(JMod.PUBLIC_STATIC_FINAL, clazz.owner().INT.array(), "few", + JExpr.arrayInit(0, 1, 2, 3, 4)); + } + + protected static void addClassArrays(JPackage root, String className) throws JCodeModelException { + addField(root._class(className)); + } + + // don't test with disabled : this feature did not exist before, there is + // nothing to use + + public void testWithDefaultOptions(final JPackage root) throws JCodeModelException { + addClassArrays(root, "DefaultArrayInitWrapOptions"); + } + + public void testWithWrapFieldBinary(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.variables.array.condition(EListWrapStrategy.BINARY); + addClassArrays(root, "WrapArrayInitBinary"); + } + + public void testWithWrapFieldRequired(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.variables.array.condition(EListWrapStrategy.REQUIRED); + addClassArrays(root, "WrapArrayInitRequired"); + } + + public void testWithWrapFieldNever(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.variables.array.condition(EListWrapStrategy.NEVER); + addClassArrays(root, "WrapArrayInitNever"); + } + + public void testWithWrapFieldAlways(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.variables.array.condition(EListWrapStrategy.ALWAYS); + addClassArrays(root, "WrapArrayInitAlways"); + } + +} diff --git a/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/variables/block/BlockVarFormatTestGen.java b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/variables/block/BlockVarFormatTestGen.java new file mode 100644 index 000000000..7bc6d2e51 --- /dev/null +++ b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/variables/block/BlockVarFormatTestGen.java @@ -0,0 +1,51 @@ +package com.helger.jcodemodel.tests.format.variables.block; + +import com.helger.jcodemodel.JDefinedClass; +import com.helger.jcodemodel.JExpr; +import com.helger.jcodemodel.JMethod; +import com.helger.jcodemodel.JMod; +import com.helger.jcodemodel.JPackage; +import com.helger.jcodemodel.compile.annotation.TestJCM; +import com.helger.jcodemodel.exceptions.JCodeModelException; +import com.helger.jcodemodel.vars.JBlockVar; +import com.helger.jcodemodel.writer.FormatterSettings; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; + +@TestJCM +public class BlockVarFormatTestGen { + + protected static void addMethods(JDefinedClass clazz) { + JMethod meth = + clazz.method(JMod.PUBLIC | JMod.STATIC, clazz.owner().VOID, "test"); + meth.body().decl(clazz.owner().CHAR, "a"); + JBlockVar b = meth.body().decl(clazz.owner().CHAR.array(), "b", JExpr.arrayInit(JExpr.lit('b'), JExpr.lit('b'))); + b.andVar("c", 1, JExpr.arrayInit(JExpr.arrayInit())); + for (int i = 2; i < 10; i++) { + char charidx = (char) ('b' + i); + b.andVar("variable_" + charidx, JExpr.arrayInit(JExpr.lit(charidx))); + } + meth.body().decl(clazz.owner()._ref(String.class).array(), "s", JExpr.arrayInit(null, null)); + } + + protected static void addClassMethod(JPackage root, String className) throws JCodeModelException { + addMethods(root._class(className)); + } + + // don't test with disabled : this feature did not exist before, there is + // nothing to use + + public void testWithDefaultOptions(final JPackage root) throws JCodeModelException { + addClassMethod(root, "DefaultWrapOptions"); + } + + public void testWithWrapBlockBinary(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.variables.block.condition(EListWrapStrategy.BINARY); + addClassMethod(root, "WrapBlockBinary"); + } + + public void testWithWrapBlockRequired(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.variables.block.condition(EListWrapStrategy.REQUIRED); + addClassMethod(root, "WrapBlockRequired"); + } + +} diff --git a/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/variables/field/FieldVarFormatTestGen.java b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/variables/field/FieldVarFormatTestGen.java new file mode 100644 index 000000000..051f86354 --- /dev/null +++ b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/format/variables/field/FieldVarFormatTestGen.java @@ -0,0 +1,47 @@ +package com.helger.jcodemodel.tests.format.variables.field; + +import com.helger.jcodemodel.JDefinedClass; +import com.helger.jcodemodel.JExpr; +import com.helger.jcodemodel.JFieldVar; +import com.helger.jcodemodel.JMod; +import com.helger.jcodemodel.JPackage; +import com.helger.jcodemodel.compile.annotation.TestJCM; +import com.helger.jcodemodel.exceptions.JCodeModelException; +import com.helger.jcodemodel.writer.FormatterSettings; +import com.helger.jcodemodel.writer.settings.Wrap.ListWrapping.EListWrapStrategy; + +@TestJCM +public class FieldVarFormatTestGen { + + protected static void addField(JDefinedClass clazz) { + clazz.field(JMod.PUBLIC_STATIC_FINAL, clazz.owner().CHAR.array(), "a", JExpr._null()); + JFieldVar b = + clazz.field(JMod.PUBLIC_STATIC_FINAL, clazz.owner().CHAR.array(), "b", JExpr.arrayInit(JExpr.lit('b'))); + b.andVar("c", 1, JExpr._null()); + for (int i = 2; i < 10; i++) { + b.andVar("variable_" + i, JExpr._null()); + } + } + + protected static void addClassMethod(JPackage root, String className) throws JCodeModelException { + addField(root._class(className)); + } + + // don't test with disabled : this feature did not exist before, there is + // nothing to use + + public void testWithDefaultOptions(final JPackage root) throws JCodeModelException { + addClassMethod(root, "DefaultWrapOptions"); + } + + public void testWithWrapFieldBinary(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.variables.field.condition(EListWrapStrategy.BINARY); + addClassMethod(root, "WrapFieldBinary"); + } + + public void testWithWrapFieldRequired(final JPackage root, FormatterSettings settings) throws JCodeModelException { + settings.wrap.variables.field.condition(EListWrapStrategy.REQUIRED); + addClassMethod(root, "WrapFieldRequired"); + } + +} diff --git a/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/samevars/SameVarsTestGen.java b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/samevars/SameVarsTestGen.java new file mode 100644 index 000000000..2ae74c518 --- /dev/null +++ b/jcodemodeltests/src/main/java/com/helger/jcodemodel/tests/samevars/SameVarsTestGen.java @@ -0,0 +1,34 @@ +package com.helger.jcodemodel.tests.samevars; + +import com.helger.jcodemodel.JDefinedClass; +import com.helger.jcodemodel.JExpr; +import com.helger.jcodemodel.JFieldVar; +import com.helger.jcodemodel.JMethod; +import com.helger.jcodemodel.JMod; +import com.helger.jcodemodel.JPackage; +import com.helger.jcodemodel.compile.annotation.TestJCM; +import com.helger.jcodemodel.exceptions.JCodeModelException; +import com.helger.jcodemodel.vars.JBlockVar; + +@TestJCM +public class SameVarsTestGen { + + public void simpleClass(final JPackage root) throws JCodeModelException { + final JDefinedClass cl = root._class("SameVarsSimpleClass"); + + JFieldVar fld = cl.field(JMod.PUBLIC | JMod.STATIC, cl.owner().INT, "i", JExpr.lit(3)); + fld.andVar("j"); + fld.andVar("k", JExpr.lit(1)); + + JFieldVar a1 = cl.field(JMod.PUBLIC | JMod.STATIC, cl.owner().CHAR.array(), "a1"); + a1.andVar("a2"); + a1.andVar("a3", 1, null); + + JMethod met = cl.method(JMod.PUBLIC | JMod.STATIC, cl.owner().VOID, "test"); + JBlockVar jvar = met.body().decl(cl.owner().INT, "i", JExpr.lit(11)); + jvar.andVar("j"); + jvar.andVar("k", JExpr.lit(5)); + + } + +} diff --git a/jcodemodeltests/src/test/java/com/helger/jcodemodel/tests/arrayinit/ArrayInitTest.java b/jcodemodeltests/src/test/java/com/helger/jcodemodel/tests/arrayinit/ArrayInitTest.java new file mode 100644 index 000000000..3953c6648 --- /dev/null +++ b/jcodemodeltests/src/test/java/com/helger/jcodemodel/tests/arrayinit/ArrayInitTest.java @@ -0,0 +1,17 @@ +package com.helger.jcodemodel.tests.arrayinit; + +import org.junit.Assert; +import org.junit.Test; + +public class ArrayInitTest { + + @Test + public void simpleClass() { + Assert.assertArrayEquals(new int[] { 0, 1, 2, 3, 4, 5 }, ArrayInitSimpleClass.i); + Assert.assertArrayEquals(new int[] {}, ArrayInitSimpleClass.i0); + Assert.assertArrayEquals(new char[] { 'a' }, ArrayInitSimpleClass.c); + Assert.assertArrayEquals(new double[] { .0, .1, .2, .3 }, ArrayInitSimpleClass.d, 0.01); + Assert.assertArrayEquals(new String[] { null, "s", "sss" }, ArrayInitSimpleClass.s); + } + +} diff --git a/jcodemodeltests/src/test/java/com/helger/jcodemodel/tests/samevars/SameVarsTest.java b/jcodemodeltests/src/test/java/com/helger/jcodemodel/tests/samevars/SameVarsTest.java new file mode 100644 index 000000000..86c618cdf --- /dev/null +++ b/jcodemodeltests/src/test/java/com/helger/jcodemodel/tests/samevars/SameVarsTest.java @@ -0,0 +1,20 @@ +package com.helger.jcodemodel.tests.samevars; + +import org.junit.Assert; +import org.junit.Test; + +public class SameVarsTest { + + @Test + public void testSimpleClass() { + Assert.assertEquals(3, SameVarsSimpleClass.i); + Assert.assertEquals(0, SameVarsSimpleClass.j); + Assert.assertEquals(1, SameVarsSimpleClass.k); + + SameVarsSimpleClass.a1 = new char[] { 'a' }; + SameVarsSimpleClass.a2 = new char[] { 'a' }; + SameVarsSimpleClass.a3 = new char[][] { { 'a' } }; + + } + +}