Do not lose newlines/tabs from javadoc
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / BaseTemplate.xtend
index f9652b65d5912539175fe0557bedf79cfc3d4bad..0ebe404e0fc9d95e63934291023cfe8f61689bcc 100644 (file)
@@ -10,107 +10,91 @@ package org.opendaylight.mdsal.binding.java.api.generator
 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.encodeAngleBrackets
 
 import com.google.common.base.CharMatcher
+import com.google.common.base.MoreObjects
 import com.google.common.base.Splitter
 import com.google.common.collect.Iterables
-import java.util.Arrays
 import java.util.Collection
-import java.util.HashMap
 import java.util.List
-import java.util.Map
+import java.util.Map.Entry
 import java.util.StringTokenizer
 import java.util.regex.Pattern
 import org.opendaylight.mdsal.binding.model.api.ConcreteType
 import org.opendaylight.mdsal.binding.model.api.Constant
 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
-import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
 import org.opendaylight.mdsal.binding.model.api.GeneratedType
+import org.opendaylight.mdsal.binding.model.api.JavaTypeName
 import org.opendaylight.mdsal.binding.model.api.MethodSignature
 import org.opendaylight.mdsal.binding.model.api.Restrictions
 import org.opendaylight.mdsal.binding.model.api.Type
 import org.opendaylight.mdsal.binding.model.api.TypeMember
 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Single
 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Multiple
+import org.opendaylight.mdsal.binding.model.util.TypeConstants
 import org.opendaylight.mdsal.binding.model.util.Types
+import org.opendaylight.mdsal.binding.spec.naming.BindingMapping
+import org.opendaylight.yangtools.yang.binding.CodeHelpers
 import org.opendaylight.yangtools.yang.common.QName
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
-import org.opendaylight.yangtools.yang.model.api.DocumentedNode
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
 import org.opendaylight.yangtools.yang.model.api.SchemaNode
-
-abstract class BaseTemplate {
-    protected val GeneratedType type;
-    protected val Map<String, String> importMap;
-
-    private static final char NEW_LINE = '\n'
-    private static final CharMatcher NL_MATCHER = CharMatcher.is(NEW_LINE)
-    private static final CharMatcher TAB_MATCHER = CharMatcher.is('\t')
-    private static final Pattern SPACES_PATTERN = Pattern.compile(" +")
-    private static final Splitter NL_SPLITTER = Splitter.on(NL_MATCHER)
-    private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
-
-    new(GeneratedType _type) {
-        if (_type === null) {
-            throw new IllegalArgumentException("Generated type reference cannot be NULL!")
-        }
-        this.type = _type;
-        this.importMap = new HashMap<String,String>()
+import org.opendaylight.yangtools.yang.model.api.YangStmtMapping
+import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement
+import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement
+import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement
+import org.opendaylight.yangtools.yang.model.export.DeclaredStatementFormatter
+
+abstract class BaseTemplate extends JavaFileTemplate {
+    static final char NEW_LINE = '\n'
+    static val AMP_MATCHER = CharMatcher.is('&')
+    static val NL_MATCHER = CharMatcher.is(NEW_LINE)
+    static val TAB_MATCHER = CharMatcher.is('\t')
+    static val SPACES_PATTERN = Pattern.compile(" +")
+    static val NL_SPLITTER = Splitter.on(NL_MATCHER)
+    static val TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
+    static val YANG_FORMATTER = DeclaredStatementFormatter.builder()
+        .addIgnoredStatement(YangStmtMapping.CONTACT)
+        .addIgnoredStatement(YangStmtMapping.DESCRIPTION)
+        .addIgnoredStatement(YangStmtMapping.REFERENCE)
+        .addIgnoredStatement(YangStmtMapping.ORGANIZATION)
+        .build();
+
+    new(GeneratedType type) {
+        super(type)
     }
 
-    def packageDefinition() '''package «type.packageName»;'''
+    new(AbstractJavaGeneratedType javaType, GeneratedType type) {
+        super(javaType, type)
+    }
 
-    final public def generate() {
+    final def generate() {
         val _body = body()
         '''
-            «packageDefinition»
-            «imports»
+            package «type.packageName»;
+            «generateImportBlock»
 
             «_body»
         '''.toString
     }
 
-    protected def imports() '''
-        «FOR entry : importMap.entrySet»
-            «IF !hasSamePackage(entry.value) && !isLocalInnerClass(entry.value)»
-                import «entry.value».«entry.key»;
-            «ENDIF»
-        «ENDFOR»
-    '''
-
-    /**
-     * Checks if packages of generated type and imported type is the same
-     *
-     * @param importedTypePackageName the package name of imported type
-     * @return true if the packages are the same false otherwise
-     */
-    final private def boolean hasSamePackage(String importedTypePackageName) {
-        return type.packageName.equals(importedTypePackageName);
-    }
-
-    def isLocalInnerClass(String importedTypePackageName) {
-        return type.fullyQualifiedName.equals(importedTypePackageName);
-    }
-
     protected abstract def CharSequence body();
 
     // Helper patterns
     final protected def fieldName(GeneratedProperty property) '''_«property.name»'''
 
     final protected def propertyNameFromGetter(MethodSignature getter) {
-        var int prefix;
-        if (getter.name.startsWith("is")) {
-            prefix = 2
-        } else if (getter.name.startsWith("get")) {
-            prefix = 3
+        var String prefix;
+        if (getter.name.startsWith(BindingMapping.BOOLEAN_GETTER_PREFIX)) {
+            prefix = BindingMapping.BOOLEAN_GETTER_PREFIX
+        } else if (getter.name.startsWith(BindingMapping.GETTER_PREFIX)) {
+            prefix = BindingMapping.GETTER_PREFIX
+        } else if (getter.name.startsWith(BindingMapping.NONNULL_PREFIX)) {
+            prefix = BindingMapping.NONNULL_PREFIX
         } else {
-            throw new IllegalArgumentException("Not a getter")
+            throw new IllegalArgumentException(getter + " is not a getter")
         }
-        return getter.name.substring(prefix).toFirstLower;
-    }
-
-    final protected def isAccessor(MethodSignature maybeGetter) {
-        return maybeGetter.name.startsWith("is") || maybeGetter.name.startsWith("get");
+        return getter.name.substring(prefix.length).toFirstLower;
     }
 
     /**
@@ -152,15 +136,6 @@ abstract class BaseTemplate {
         }
     '''
 
-    final protected def importedName(Type intype) {
-        GeneratorUtil.putTypeIntoImports(type, intype, importMap);
-        GeneratorUtil.getExplicitType(type, intype, importMap)
-    }
-
-    final protected def importedName(Class<?> cls) {
-        importedName(Types.typeForClass(cls))
-    }
-
     /**
      * Template method which generates method parameters with their types from <code>parameters</code>.
      *
@@ -199,13 +174,11 @@ abstract class BaseTemplate {
         '''
     }
 
-    def String wrapToDocumentation(String text) {
+    def static String wrapToDocumentation(String text) {
         if (text.empty)
             return ""
 
-        val StringBuilder sb = new StringBuilder("/**")
-        sb.append(NEW_LINE)
-
+        val StringBuilder sb = new StringBuilder().append("/**\n")
         for (String t : NL_SPLITTER.split(text)) {
             sb.append(" *")
             if (!t.isEmpty()) {
@@ -235,8 +208,6 @@ abstract class BaseTemplate {
         '''.toString
     }
 
-    private static val AMP_MATCHER = CharMatcher.is('&')
-
     def static encodeJavadocSymbols(String description) {
         if (description.nullOrEmpty) {
             return description;
@@ -272,19 +243,19 @@ abstract class BaseTemplate {
             val def = optDef.get
             sb.append(NEW_LINE)
 
-               if (def instanceof Single) {
+            if (def instanceof Single) {
                 val node = def.node
                 sb.append("<p>\n")
                 .append("This class represents the following YANG schema fragment defined in module <b>")
-                .append(def.module.name).append("</b>\n")
+                .append(def.module.argument).append("</b>\n")
                 .append("<pre>\n")
-                .append(encodeAngleBrackets(encodeJavadocSymbols(YangTemplate.generateYangSnippet(node))))
-                .append("</pre>")
+                appendYangSnippet(sb, def.module, (node as EffectiveStatement<?, ?>).declared)
+                sb.append("</pre>")
 
                 if (node instanceof SchemaNode) {
                     sb.append("The schema path to identify an instance is\n")
                     .append("<i>")
-                    .append(formatSchemaPath(def.module.name, node.path.pathFromRoot))
+                    .append(formatSchemaPath(def.module.argument, node.path.pathFromRoot))
                     .append("</i>\n")
 
                     if (hasBuilderClass(node)) {
@@ -302,16 +273,23 @@ abstract class BaseTemplate {
                         }
                     }
                 }
-               } else if (def instanceof Multiple) {
+            } else if (def instanceof Multiple) {
                 sb.append("<pre>\n")
-                for (DocumentedNode schemaNode : def.nodes) {
-                    sb.append(encodeAngleBrackets(encodeJavadocSymbols(YangTemplate.generateYangSnippet(schemaNode))))
+                for (SchemaNode node : def.nodes) {
+                    appendYangSnippet(sb, def.module, (node as EffectiveStatement<?, ?>).declared)
                 }
                 sb.append("</pre>\n")
             }
         }
     }
 
+    def private static void appendYangSnippet(StringBuilder sb, ModuleEffectiveStatement module,
+            DeclaredStatement<?> stmt) {
+        for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
+            sb.append(encodeAngleBrackets(encodeJavadocSymbols(str)))
+        }
+    }
+
     def private static boolean hasBuilderClass(SchemaNode schemaNode) {
         return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
                 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
@@ -333,7 +311,7 @@ abstract class BaseTemplate {
         return sb.toString();
     }
 
-    def protected String formatDataForJavaDoc(TypeMember type, String additionalComment) {
+    def protected static String formatDataForJavaDoc(TypeMember type, String additionalComment) {
         val StringBuilder typeDescriptionBuilder = new StringBuilder();
         if (!type.comment.nullOrEmpty) {
             typeDescriptionBuilder.append(formatToParagraph(type.comment))
@@ -375,7 +353,7 @@ abstract class BaseTemplate {
         return sb.toString
     }
 
-    protected def formatToParagraph(String text) {
+    protected static def formatToParagraph(String text) {
         if(text === null || text.isEmpty)
             return text
 
@@ -385,8 +363,8 @@ abstract class BaseTemplate {
         var boolean isFirstElementOnNewLineEmptyChar = false;
 
         formattedText = encodeJavadocSymbols(formattedText)
-        formattedText = NL_MATCHER.removeFrom(formattedText)
-        formattedText = TAB_MATCHER.removeFrom(formattedText)
+        formattedText = NL_MATCHER.replaceFrom(formattedText, ' ')
+        formattedText = TAB_MATCHER.replaceFrom(formattedText, ' ')
         formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
 
         val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
@@ -429,41 +407,17 @@ abstract class BaseTemplate {
 
     def protected generateToString(Collection<GeneratedProperty> properties) '''
         «IF !properties.empty»
-            @Override
+            @«Override.importedName»
             public «String.importedName» toString() {
-                «StringBuilder.importedName» builder = new «StringBuilder.importedName»(«type.importedName».class.getSimpleName()).append(" [");
-                boolean first = true;
-
+                final «MoreObjects.importedName».ToStringHelper helper = «MoreObjects.importedName».toStringHelper(«type.importedName».class);
                 «FOR property : properties»
-                    if («property.fieldName» != null) {
-                        if (first) {
-                            first = false;
-                        } else {
-                            builder.append(", ");
-                        }
-                        builder.append("«property.fieldName»=");
-                        «IF property.returnType.name.contains("[")»
-                            builder.append(«Arrays.importedName».toString(«property.fieldName»));
-                        «ELSE»
-                            builder.append(«property.fieldName»);
-                        «ENDIF»
-                    }
+                    «CodeHelpers.importedName».appendValue(helper, "«property.fieldName»", «property.fieldName»);
                 «ENDFOR»
-                return builder.append(']').toString();
+                return helper.toString();
             }
         «ENDIF»
     '''
 
-    def getRestrictions(Type type) {
-        var Restrictions restrictions = null
-        if (type instanceof ConcreteType) {
-            restrictions = type.restrictions
-        } else if (type instanceof GeneratedTransferObject) {
-            restrictions = type.restrictions
-        }
-        return restrictions
-    }
-
     /**
      * Template method which generates method parameters with their types from <code>parameters</code>.
      *
@@ -479,28 +433,55 @@ abstract class BaseTemplate {
         ENDIF
     »'''
 
-    def protected GeneratedProperty findProperty(GeneratedTransferObject gto, String name) {
-        val props = gto.properties
-        for (prop : props) {
-            if (prop.name.equals(name)) {
-                return prop
-            }
-        }
-        val GeneratedTransferObject parent = gto.superType
-        if (parent !== null) {
-            return findProperty(parent, name)
-        }
-        return null
-    }
-
     def protected emitConstant(Constant c) '''
-        «IF c.value instanceof QName»
-            «val qname = c.value as QName»
-            «val rev = qname.revision»
-            public static final «c.type.importedName» «c.name» = «QName.name».create("«qname.namespace.toString»",
-                «IF rev.isPresent»"«rev.get»", «ENDIF»"«qname.localName»").intern();
+        «IF BindingMapping.QNAME_STATIC_FIELD_NAME.equals(c.name)»
+            «val entry = c.value as Entry<JavaTypeName, String>»
+            public static final «c.type.importedNonNull» «c.name» = «entry.key.importedName».«BindingMapping.MODULE_INFO_QNAMEOF_METHOD_NAME»("«entry.value»");
         «ELSE»
             public static final «c.type.importedName» «c.name» = «c.value»;
         «ENDIF»
     '''
+
+    def protected generateCheckers(GeneratedProperty field, Restrictions restrictions, Type actualType) '''
+       «IF restrictions.rangeConstraint.present»
+           «AbstractRangeGenerator.forType(actualType).generateRangeChecker(field.name.toFirstUpper,
+               restrictions.rangeConstraint.get, this)»
+       «ENDIF»
+       «IF restrictions.lengthConstraint.present»
+           «LengthGenerator.generateLengthChecker(field.fieldName.toString, actualType, restrictions.lengthConstraint.get, this)»
+       «ENDIF»
+    '''
+
+    def protected checkArgument(GeneratedProperty property, Restrictions restrictions, Type actualType, String value) '''
+       «IF restrictions.getRangeConstraint.isPresent»
+           «IF actualType instanceof ConcreteType»
+               «AbstractRangeGenerator.forType(actualType).generateRangeCheckerCall(property.getName.toFirstUpper, value)»
+           «ELSE»
+               «AbstractRangeGenerator.forType(actualType).generateRangeCheckerCall(property.getName.toFirstUpper, value + ".getValue()")»
+           «ENDIF»
+       «ENDIF»
+       «IF restrictions.getLengthConstraint.isPresent»
+           «IF actualType instanceof ConcreteType»
+               «LengthGenerator.generateLengthCheckerCall(property.fieldName.toString, value)»
+           «ELSE»
+               «LengthGenerator.generateLengthCheckerCall(property.fieldName.toString, value + ".getValue()")»
+           «ENDIF»
+       «ENDIF»
+
+       «val fieldUpperCase = property.fieldName.toString.toUpperCase()»
+       «FOR currentConstant : type.getConstantDefinitions»
+           «IF currentConstant.getName.startsWith(TypeConstants.PATTERN_CONSTANT_NAME)
+               && fieldUpperCase.equals(currentConstant.getName.substring(TypeConstants.PATTERN_CONSTANT_NAME.length))»
+           «CodeHelpers.importedName».checkPattern(value, «Constants.MEMBER_PATTERN_LIST»«property.fieldName», «Constants.MEMBER_REGEX_LIST»«property.fieldName»);
+           «ENDIF»
+       «ENDFOR»
+    '''
+
+    def protected hashCodeResult(Collection<GeneratedProperty> properties) '''
+        final int prime = 31;
+        int result = 1;
+        «FOR property : properties»
+            result = prime * result + «property.importedUtilClass».hashCode(«property.fieldName»);
+        «ENDFOR»
+    '''
 }