This is an automated email from the ASF dual-hosted git repository.

aradzinski pushed a commit to branch NLPCRAFT-473
in repository https://gitbox.apache.org/repos/asf/incubator-nlpcraft.git


The following commit(s) were added to refs/heads/NLPCRAFT-473 by this push:
     new b4c87df  Code review + fixes.
b4c87df is described below

commit b4c87dfbaad1c3b5b3d21e17cd487d54aa73a7de
Author: Aaron Radzinski <[email protected]>
AuthorDate: Sat Jan 29 12:04:40 2022 -0800

    Code review + fixes.
---
 .../nlpcraft/internal/antlr4/NCCompilerUtils.scala |  19 +-
 .../nlpcraft/internal/impl/NCModelScanner.scala    | 208 +++++++++------------
 .../intent/compiler/NCIDLCompilerSpec.scala        |   6 +-
 3 files changed, 97 insertions(+), 136 deletions(-)

diff --git 
a/nlpcraft/src/main/scala/org/apache/nlpcraft/internal/antlr4/NCCompilerUtils.scala
 
b/nlpcraft/src/main/scala/org/apache/nlpcraft/internal/antlr4/NCCompilerUtils.scala
index 540bd0f..e301c2a 100644
--- 
a/nlpcraft/src/main/scala/org/apache/nlpcraft/internal/antlr4/NCCompilerUtils.scala
+++ 
b/nlpcraft/src/main/scala/org/apache/nlpcraft/internal/antlr4/NCCompilerUtils.scala
@@ -32,14 +32,17 @@ object NCCompilerUtils:
       * @return
       */
     def mkErrorHolder(in: String, charPos: Int): CompilerErrorHolder =
-        val charPos0 = charPos - (in.length - in.stripLeading().length)
         val in0 = in.strip()
-        val pos = Math.max(0, charPos0)
-        val dash = "-" * in0.length
 
-        var ptrStr = s"${dash.substring(0, pos)}^"
-        if pos < dash.length - 1 then ptrStr = s"$ptrStr${dash.substring(pos + 
1)}"
-        else ptrStr = s"$ptrStr${dash.substring(pos + 1)}"
+        if in0.isEmpty || charPos < 0 then CompilerErrorHolder("<empty>", 
"<empty>")
+        else
+            val charPos0 = charPos - (in.length - in.stripLeading().length)
+            val pos = Math.max(0, charPos0)
+            val dash = "-" * in0.length
 
-        val origStr = s"${in0.substring(0, 
pos)}${in0.charAt(pos)}${in0.substring(pos + 1)}"
-        CompilerErrorHolder(ptrStr, origStr)
+            var ptrStr = s"${dash.substring(0, pos)}^"
+            if pos < dash.length - 1 then ptrStr = 
s"$ptrStr${dash.substring(pos + 1)}"
+            else ptrStr = s"$ptrStr${dash.substring(pos + 1)}"
+
+            val origStr = s"${in0.substring(0, 
pos)}${in0.charAt(pos)}${in0.substring(pos + 1)}"
+            CompilerErrorHolder(ptrStr, origStr)
diff --git 
a/nlpcraft/src/main/scala/org/apache/nlpcraft/internal/impl/NCModelScanner.scala
 
b/nlpcraft/src/main/scala/org/apache/nlpcraft/internal/impl/NCModelScanner.scala
index 3e37363..7b37671 100644
--- 
a/nlpcraft/src/main/scala/org/apache/nlpcraft/internal/impl/NCModelScanner.scala
+++ 
b/nlpcraft/src/main/scala/org/apache/nlpcraft/internal/impl/NCModelScanner.scala
@@ -45,7 +45,7 @@ import scala.util.Using
 case class NCModelIntent(intent: NCIDLIntent, function: NCIntentMatch => 
NCResult, samples: Seq[Seq[String]])
 
 /**
-  * TODO: common comment for annotations usage. Do not apply annotations for 
unused private methods and fields. Compiler can drop them.
+  *
   */
 object NCModelScanner extends LazyLogging:
     private final val CLS_INTENT = classOf[NCIntent]
@@ -65,6 +65,12 @@ object NCModelScanner extends LazyLogging:
 
     private final val CLS_ENTITY = classOf[NCEntity]
 
+    private lazy val I = "@NCIntent"
+    private lazy val IT = "@NCIntentTerm"
+    private lazy val IR = "@NCIntentRef"
+    private lazy val S = "@NCIntentSample"
+    private lazy val SR = "@NCIntentSampleRef"
+
     private final val COMP_CLS: Set[Class[_]] = Set(
         CLS_SCALA_SEQ,
         CLS_SCALA_LST,
@@ -121,7 +127,6 @@ object NCModelScanner extends LazyLogging:
         val cls = class2Str(mtd.getDeclaringClass)
         val name = mtd.getName
         val args = mtd.getParameters.map(_.getType.getSimpleName).mkString(", 
")
-
         s"$cls#$name($args)"
 
     /**
@@ -132,28 +137,27 @@ object NCModelScanner extends LazyLogging:
     private def field2Str(f: Field): String =
         val cls = class2Str(f.getDeclaringClass)
         val name = f.getName
-
         s"$cls.$name"
 
     /**
       *
       * @param cfg
       * @param mtd
-      * @param paramClss
+      * @param prmClss
       * @param argsList
-      * @param ctxFirstParam
+      * @param ctxFirstPrm
       * @return
       */
-    private def prepareParams(cfg: NCModelConfig, mtd: Method, paramClss: 
Seq[Class[_]], argsList: Seq[util.List[NCEntity]], ctxFirstParam: Boolean): 
Seq[AnyRef] =
-        paramClss.zip(argsList).zipWithIndex.map { case ((paramCls, argList), 
i) =>
-            def mkArg(): String = arg2Str(mtd, i, ctxFirstParam)
+    private def prepareParams(cfg: NCModelConfig, mtd: Method, prmClss: 
Seq[Class[_]], argsList: Seq[util.List[NCEntity]], ctxFirstPrm: Boolean): 
Seq[AnyRef] =
+        prmClss.zip(argsList).zipWithIndex.map { case ((paramCls, argList), i) 
=>
+            def mkArg(): String = arg2Str(mtd, i, ctxFirstPrm)
 
+            lazy val z = s"mdlId=${cfg.getId}, type=$paramCls, arg=${mkArg()}"
             val entsCnt = argList.size()
 
             // Single entity.
             if paramCls == CLS_ENTITY then
-                if entsCnt != 1 then
-                    E(s"Expected single entity (found $entsCnt) in 
@NCIntentTerm annotated argument [mdlId=${cfg.getId}, arg=${mkArg()}]")
+                if entsCnt != 1 then E(s"Expected single entity (found 
$entsCnt) in $IT annotated argument [$z]")
 
                 argList.get(0)
             // Array of entities.
@@ -171,53 +175,48 @@ object NCModelScanner extends LazyLogging:
                 entsCnt match
                     case 0 => None
                     case 1 => Option(argList.get(0))
-                    case _ => E(s"Too many entities ($entsCnt) for 
scala.Option[_] @NCIntentTerm annotated argument [mdlId=${cfg.getId}, 
arg=${mkArg()}]")
+                    case _ => E(s"Too many entities ($entsCnt) for 
'scala.Option[_]' $IT annotated argument [$z]")
             else if paramCls == CLS_JAVA_OPT then
                 entsCnt match
                     case 0 => util.Optional.empty()
                     case 1 => util.Optional.of(argList.get(0))
-                    case _ => E(s"Too many entities ($entsCnt) for 
java.util.Optional @NCIntentTerm annotated argument [mdlId=${cfg.getId}, 
arg=${mkArg()}]")
+                    case _ => E(s"Too many entities ($entsCnt) for 
'java.util.Optional' $IT annotated argument [$z]")
             else
                 // All allowed arguments types already checked.
-                throw new AssertionError(s"Unexpected callback @NCIntentTerm 
argument type [mdlId=${cfg.getId}, type=$paramCls, arg=${mkArg()}]")
+                throw new AssertionError(s"Unexpected type for callback's $IT 
argument [$z]")
         }
 
     /**
       *
       * @param cfg
-      * @param method
+      * @param mtd
       * @param obj
       * @param args
       * @return
       */
-    private def invoke(cfg: NCModelConfig, method: Method, obj: AnyRef, args: 
scala.Array[AnyRef]): NCResult =
-        val methodObj = if Modifier.isStatic(method.getModifiers) then null 
else obj
-        var flag = method.canAccess(methodObj)
-
+    private def invoke(cfg: NCModelConfig, mtd: Method, obj: AnyRef, args: 
scala.Array[AnyRef]): NCResult =
+        val methodObj = if Modifier.isStatic(mtd.getModifiers) then null else 
obj
+        var flag = mtd.canAccess(methodObj)
+        lazy val z = s"mdlId=${cfg.getId}, callback=${method2Str(mtd)}"
         try
             if !flag then
-                method.setAccessible(true)
-
+                mtd.setAccessible(true)
                 flag = true
             else
                 flag = false
-
-            method.invoke(methodObj, args: _*).asInstanceOf[NCResult]
+            mtd.invoke(methodObj, args: _*).asInstanceOf[NCResult]
         catch
             case e: InvocationTargetException =>
                 e.getTargetException match
                     case cause: NCIntentSkip => throw cause
                     case cause: NCRejection => throw cause
                     case cause: NCException => throw cause
-                    case cause: Throwable => E(s"Intent callback invocation 
error [mdlId=${cfg.getId}, callback=${method2Str(method)}]", cause)
-
-            case e: Throwable => E(s"Unexpected intent callback invocation 
error [mdlId=${cfg.getId}, callback=${method2Str(method)}]", e)
+                    case cause: Throwable => E(s"Intent callback invocation 
error [$z]", cause)
+            case e: Throwable => E(s"Unexpected intent callback invocation 
error [$z]", e)
         finally
             if flag then
-                try
-                    method.setAccessible(false)
-                catch
-                    case e: SecurityException => E(s"Access or security error 
in intent callback [mdlId=${cfg.getId}, callback=${method2Str(method)}]", e)
+                try mtd.setAccessible(false)
+                catch case e: SecurityException => E(s"Access or security 
error in intent callback [$z]", e)
 
     /**
       *
@@ -230,30 +229,22 @@ object NCModelScanner extends LazyLogging:
         lazy val fStr = field2Str(field)
         val fieldObj = if Modifier.isStatic(field.getModifiers) then null else 
obj
         var flag = field.canAccess(fieldObj)
+        lazy val z = s"mdlId=${cfg.getId}, field=$fStr"
         val res =
             try
                 if !flag then
                     field.setAccessible(true)
-
                     flag = true
                 else
                     flag = false
-
                 field.get(fieldObj)
-            catch
-                // TODO: text
-                case e: Throwable => E(s"Unexpected field access error 
[mdlId=${cfg.getId}, field=$fStr]", e)
+            catch case e: Throwable => E(s"Unexpected field access error 
[$z]", e)
             finally
                 if flag then
-                    try
-                        field.setAccessible(false)
-                    catch
-                        // TODO: text
-                        case e: SecurityException => E(s"Access or security 
error in field [mdlId=${cfg.getId}, field=$fStr]", e)
-
-        if res == null then
-            throw new NCException(s"Value is null for: $fStr") // TODO: text
+                    try field.setAccessible(false)
+                    catch case e: SecurityException => E(s"Access or security 
error in field [$z]", e)
 
+        if res == null then throw new NCException(s"Field value cannot be 
'null' for [$z]")
         res
 
     /**
@@ -272,8 +263,8 @@ object NCModelScanner extends LazyLogging:
       * @return Methods.
       */
     private def getAllMethods(o: AnyRef): Set[Method] =
-        val claxx = o.getClass
-        (claxx.getDeclaredMethods ++ claxx.getMethods).toSet
+        val cls = o.getClass
+        (cls.getDeclaredMethods ++ cls.getMethods).toSet
 
     /**
       * Gets its own fields including private and accessible from parents.
@@ -282,8 +273,8 @@ object NCModelScanner extends LazyLogging:
       * @return Fields.
       */
     private def getAllFields(o: AnyRef): Set[Field] =
-        val claxx = o.getClass
-        (claxx.getDeclaredFields ++ claxx.getFields).toSet
+        val cls = o.getClass
+        (cls.getDeclaredFields ++ cls.getFields).toSet
 
     /**
       *
@@ -297,46 +288,35 @@ object NCModelScanner extends LazyLogging:
         lazy val mtdStr = method2Str(mtd)
         lazy val intAnns = mtd.getAnnotationsByType(CLS_INTENT)
         lazy val refAnns = mtd.getAnnotationsByType(CLS_INTENT_REF)
-
         lazy val samples = mutable.HashMap.empty[String, Seq[Seq[String]]]
 
         if smpAnns.nonEmpty || smpAnnsRef.nonEmpty then
             if intAnns.isEmpty && refAnns.isEmpty then
-                E(s"@NCIntentSample or @NCIntentSampleRef annotations without 
corresponding @NCIntent or @NCIntentRef annotations: $mtdStr")
+                E(s"$S or $SR annotations without corresponding $I or $IR 
annotations: $mtdStr")
             else
                 def read[T](annArr: scala.Array[T], annName: String, 
getSamples: T => Seq[String], getSource: Option[T => String]): Seq[Seq[String]] 
=
                     for (ann <- annArr.toSeq) yield
                         val samples = getSamples(ann).map(_.strip).filter(s => 
s.nonEmpty && s.head != '#')
-
                         if samples.isEmpty then
                             getSource match
                                 case None => logger.warn(s"$annName annotation 
has no samples: $mtdStr")
                                 case Some(f) => logger.warn(s"$annName 
annotation references '${f(ann)}' file that has no samples: $mtdStr")
-
                             Seq.empty
                         else
-                            samples
-                                .filter(_.nonEmpty)
+                            samples.filter(_.nonEmpty)
 
                 val seqSeq =
-                    read[NCIntentSample](
-                        smpAnns, "@NCIntentSample", _.value.toSeq, None
-                    ) ++
-                    read[NCIntentSampleRef](
-                        smpAnnsRef, "@NCIntentSampleRef", a => 
NCUtils.readResource(a.value), Option(_.value)
-                    )
+                    read[NCIntentSample](smpAnns, S, _.value.toSeq, None) ++
+                    read[NCIntentSampleRef](smpAnnsRef, SR, a => 
NCUtils.readResource(a.value), Option(_.value))
 
                 if NCUtils.containsDups(seqSeq.flatMap(_.toSeq).toList) then
-                    logger.warn(s"@NCIntentSample and @NCIntentSampleRef 
annotations have duplicates: $mtdStr")
+                    logger.warn(s"$S and $SR annotations have duplicates: 
$mtdStr")
 
                 val distinct = seqSeq.map(_.distinct).distinct
-
-                for (ann <- intAnns; intent <- 
NCIDLCompiler.compile(ann.value, cfg, mtdStr))
-                    samples += intent.id -> distinct
-
+                for (ann <- intAnns; intent <- 
NCIDLCompiler.compile(ann.value, cfg, mtdStr)) samples += intent.id -> distinct
                 for (ann <- refAnns) samples += ann.value -> distinct
         else if intAnns.nonEmpty || refAnns.nonEmpty then
-            logger.warn(s"@NCIntentSample or @NCIntentSampleRef annotations 
are missing for: $mtdStr")
+            logger.warn(s"$S or $SR annotations are missing for: $mtdStr")
 
         samples.toMap
 
@@ -356,53 +336,49 @@ object NCModelScanner extends LazyLogging:
         argClasses.zip(paramGenTypes).zipWithIndex.foreach { case ((argClass, 
paramGenType), i) =>
             def mkArg(): String = arg2Str(mtd, i, ctxFirstParam)
 
+            lazy val z = s"mdlId=${cfg.getId}, type=${class2Str(argClass)}, 
arg=${mkArg()}"
+
             // Entity.
             if argClass == CLS_ENTITY then () // No-op.
             else if argClass.isArray then
                 val compType = argClass.getComponentType
-
                 if compType != CLS_ENTITY then
-                    E(s"Unexpected array element type for @NCIntentTerm 
annotated argument [mdlId=${cfg.getId}, origin=${cfg.getOrigin}, 
type=${class2Str(compType)}, arg=${mkArg()}]")
+                    E(s"Unexpected array element type for $IT annotated 
argument [$z]")
                 // Entities collection and optionals.
             else if COMP_CLS.contains(argClass) then
                 paramGenType match
                     case pt: ParameterizedType =>
                         val actTypes = pt.getActualTypeArguments
                         val compTypes = if actTypes == null then Seq.empty 
else actTypes.toSeq
-
                         if compTypes.sizeIs != 1 then
-                            E(s"Unexpected generic types count for 
@NCIntentTerm annotated argument [mdlId=${cfg.getId}, origin=${cfg.getOrigin}, 
count=${compTypes.length}, arg=${mkArg()}]")
-
+                            E(s"Unexpected generic types count for $IT 
annotated argument [count=${compTypes.length}, $z]")
                         val compType = compTypes.head
-
                         compType match
                             // Java, Scala, Groovy.
                             case _: Class[_] =>
                                 val genClass = 
compTypes.head.asInstanceOf[Class[_]]
                                 if genClass != CLS_ENTITY then
-                                    E(s"Unexpected generic type for 
@NCIntentTerm annotated argument [mdlId=${cfg.getId}, origin=${cfg.getOrigin}, 
type=${class2Str(genClass)}, arg=${mkArg()}]")
-
+                                    E(s"Unexpected generic type for $IT 
annotated argument [$z]")
                             // Kotlin.
                             case _: WildcardType =>
                                 val wildcardType = 
compTypes.head.asInstanceOf[WildcardType]
                                 val lowBounds = wildcardType.getLowerBounds
                                 val upBounds = wildcardType.getUpperBounds
                                 if lowBounds.nonEmpty || upBounds.size != 1 || 
upBounds(0) != CLS_ENTITY then
-                                    E(s"Unexpected Kotlin generic type for 
@NCIntentTerm annotated argument [mdlId=${cfg.getId}, origin=${cfg.getOrigin}, 
type=${wc2Str(wildcardType)}, arg=${mkArg()}]")
-
-                            case _ => E(s"Unexpected generic type for 
@NCIntentTerm annotated argument [mdlId=${cfg.getId}, origin=${cfg.getOrigin}, 
type=${compType.getTypeName}, arg=${mkArg()}]")
+                                    E(s"Unexpected Kotlin generic type for $IT 
annotated argument [$z]")
+                            case _ => E(s"Unexpected generic type for $IT 
annotated argument [$z]")
                     case _ =>
                         // Scala.
                         if COMP_CLS.exists(_ == paramGenType) then
                             if !warned then
-                                warned = true // TODO: text
-                                logger.warn(s"Method arguments types cannot be 
detected and checked: ${method2Str(mtd)}")
+                                warned = true
+                                logger.warn(s"Unable to detected and 
type-check method argument [${method2Str(mtd)}, $z]")
                             end if
                         else
-                            E(s"Unexpected parameter type for @NCIntentTerm 
annotated argument [mdlId=${cfg.getId}, origin=${cfg.getOrigin}, 
type=${paramGenType.getTypeName}, arg=${mkArg()}]")
-            // Other types.
+                            E(s"Unexpected parameter type for $IT annotated 
argument [$z]")
             else
-                E(s"Unexpected parameter type for @NCIntentTerm annotated 
argument [mdlId=${cfg.getId}, origin=${cfg.getOrigin}, 
type=${class2Str(argClass)}, arg=${mkArg()}]")
+                // Other types.
+                E(s"Unexpected parameter type for $IT annotated argument [$z]")
         }
 
     /**
@@ -419,21 +395,21 @@ object NCModelScanner extends LazyLogging:
         paramCls.zip(limits).zipWithIndex.foreach { case ((cls, (min, max)), 
i) =>
             def mkArg(): String = arg2Str(mtd, i, ctxFirstParam)
 
-            val p1 = "its @NCIntentTerm annotated argument"
-            val p2 = s"[mdlId=${cfg.getId}, origin=${cfg.getOrigin}, 
arg=${mkArg()}]"
+            val p1 = "its $IT annotated argument"
+            val p2 = s"mdlId=${cfg.getId}, arg=${mkArg()}"
 
             // Argument is single entity but defined as not single entity.
             if cls == CLS_ENTITY && (min != 1 || max != 1) then
-                E(s"Intent term must have [1,1] quantifier because $p1 is a 
single value $p2")
+                E(s"Intent term must have [1,1] quantifier because $p1 is a 
single value [$p2]")
             // Argument is not single entity but defined as single entity.
             else if cls != CLS_ENTITY && (min == 1 && max == 1) then
-                E(s"Intent term has [1,1] quantifier but $p1 is not a single 
value $p2")
+                E(s"Intent term has [1,1] quantifier but $p1 is not a single 
value [$p2]")
             // Argument is optional but defined as not optional.
             else if (cls == CLS_SCALA_OPT || cls == CLS_JAVA_OPT) && (min != 0 
|| max != 1) then
-                E(s"Intent term must have [0,1] quantifier because $p1 is 
optional $p2")
+                E(s"Intent term must have [0,1] quantifier because $p1 is 
optional [$p2]")
             // Argument is not optional but defined as optional.
             else if (cls != CLS_SCALA_OPT && cls != CLS_JAVA_OPT) && (min == 0 
&& max == 1) then
-                E(s"Intent term has [0,1] quantifier but $p1 is not optional 
$p2")
+                E(s"Intent term has [0,1] quantifier but $p1 is not optional 
[$p2]")
         }
 
     /**
@@ -445,9 +421,10 @@ object NCModelScanner extends LazyLogging:
       * @return
       */
     private def prepareCallback(cfg: NCModelConfig, method: Method, obj: 
AnyRef, intent: NCIDLIntent): NCIntentMatch => NCResult =
+        lazy val z = s"mdlId=${cfg.getId}, intentId=${intent.id}, 
type=${class2Str(method.getReturnType)}, callback=${method2Str(method)}"
+
         // Checks method result type.
-        if method.getReturnType != CLS_QRY_RES then
-            E(s"Unexpected result type for @NCIntent annotated method 
[mdlId=${cfg.getId}, intentId=${intent.id}, 
type=${class2Str(method.getReturnType)}, callback=${method2Str(method)}]")
+        if method.getReturnType != CLS_QRY_RES then E(s"Unexpected result type 
for @NCIntent annotated method [$z]")
 
         val allParamTypes = method.getParameterTypes.toSeq
         val ctxFirstParam = allParamTypes.nonEmpty && allParamTypes.head == 
CLS_INTENT_MATCH
@@ -463,7 +440,7 @@ object NCModelScanner extends LazyLogging:
 
         // Checks entities parameters annotations count.
         if tokParamAnns.sizeIs != tokParamTypes.length then
-            E(s"Unexpected annotations count for @NCIntent annotated method 
[mdlId=${cfg.getId}, intentId=${intent.id}, count=${tokParamAnns.size}, 
callback=${method2Str(method)}]")
+            E(s"Unexpected annotations count for $I annotated method 
[count=${tokParamAnns.size}, $z]")
 
         // Gets terms IDs.
         val termIds = tokParamAnns.toList.zipWithIndex.map {
@@ -472,20 +449,17 @@ object NCModelScanner extends LazyLogging:
 
                 val termAnns = annArr.filter(_.isInstanceOf[NCIntentTerm])
 
-                // Each method arguments (second and later) must have one 
NCIntentTerm annotation.
+                // Each method arguments (second and later) must have one 
'NCIntentTerm' annotation.
                 termAnns.length match
                     case 1 => termAnns.head.asInstanceOf[NCIntentTerm].value
                     case 0 =>
-                        if idx == 0 then
-                            E(s"Missing @NCIntentTerm annotation or wrong type 
of the 1st parameter (must be 'NCIntentMatch') for [mdlId=${cfg.getId}, 
intentId=${intent.id}, arg=${mkArg()}]")
-                        else
-                            E(s"Missing @NCIntentTerm annotation for 
[mdlId=${cfg.getId}, intentId=${intent.id}, arg=${mkArg()}]")
-
-                    case _ => E(s"Too many @NCIntentTerm annotations for 
[mdlId=${cfg.getId}, intentId=${intent.id}, arg=${mkArg()}]")
+                        if idx == 0 then E(s"Missing $IT annotation or wrong 
type of the 1st parameter (must be 'NCIntentMatch') for [$z]")
+                        else E(s"Missing $IT annotation for [$z]")
+                    case _ => E(s"Too many $IT annotations for [$z]")
         }
 
         if NCUtils.containsDups(termIds) then
-            E(s"Duplicate term IDs in @NCIntentTerm annotations 
[mdlId=${cfg.getId}, intentId=${intent.id}, 
dups=${NCUtils.getDups(termIds).mkString(", ")}, 
callback=${method2Str(method)}]")
+            E(s"Duplicate term IDs in $IT annotations 
[dups=${NCUtils.getDups(termIds).mkString(", ")}, $z]")
 
         val terms = intent.terms
 
@@ -496,23 +470,20 @@ object NCModelScanner extends LazyLogging:
 
         if invalidIds.nonEmpty then
             // Report only the first one for simplicity & clarity.
-            E(s"Unknown term ID in @NCIntentTerm annotation 
[mdlId=${cfg.getId}, intentId=${intent.id}, termId=${invalidIds.head}, 
callback=${method2Str(method)}]")
-
-        val paramGenTypes = 
getSeq(method.getGenericParameterTypes.toIndexedSeq)
+            E(s"Unknown term ID in $IT annotation [termId=${invalidIds.head}, 
$z]")
 
         // Checks parameters.
+        val paramGenTypes = 
getSeq(method.getGenericParameterTypes.toIndexedSeq)
         checkTypes(cfg, method, tokParamTypes, paramGenTypes, ctxFirstParam)
 
         // Checks limits.
         val allLimits = terms.map(t => t.id.orNull -> (t.min, t.max)).toMap
-
         checkMinMax(cfg, method, tokParamTypes, termIds.map(allLimits), 
ctxFirstParam)
 
         (ctx: NCIntentMatch) =>
             val args = mutable.Buffer.empty[AnyRef]
             if ctxFirstParam then args += ctx
             args ++= prepareParams(cfg, method, tokParamTypes, 
termIds.map(ctx.getTermEntities), ctxFirstParam)
-
             invoke(cfg, method, obj, args.toArray)
 
     /**
@@ -523,7 +494,7 @@ object NCModelScanner extends LazyLogging:
         require(mdl != null)
 
         val cfg = mdl.getConfig
-
+        lazy val z = s"mdlId=${cfg.getId}"
         val intents = mutable.Buffer.empty[IntentHolder]
         val intentDecls = mutable.HashMap.empty[String, NCIDLIntent]
         val objs = mutable.Buffer.empty[AnyRef]
@@ -532,31 +503,21 @@ object NCModelScanner extends LazyLogging:
 
         def addDecl(intent: NCIDLIntent): Unit =
             intentDecls.get(intent.id) match
-                case Some(ex) =>
-                    if ex.idl != intent.idl then
-                        // TODO: text
-                        E(s"Intent with given ID already found with different 
definition [mdlId=${cfg.getId}, origin=${cfg.getOrigin}, id=${intent.id}]")
+                case Some(ex) => if ex.idl != intent.idl then E(s"Intent with 
given ID already found with different definition [$z, id=${intent.id}]")
                 case None => // No-op.
-
             intentDecls += intent.id -> intent
 
         def addIntent(intent: NCIDLIntent, mtd: Method, obj: AnyRef): Unit =
-            if intents.exists(_.method == mtd) then
-                // TODO: text
-                E(s"The callback cannot have more one intent 
[mdlId=${cfg.getId}, origin=${cfg.getOrigin}, callback=${method2Str(mtd)}]")
-
+            if intents.exists(_.method == mtd) then E(s"The callback cannot 
have more one intent [$z, callback=${method2Str(mtd)}]")
             intents += IntentHolder(cfg, intent, obj, mtd)
 
-        def processClassAnnotations(claxx: Class[_]): Unit =
-            if claxx != null && processed.add(claxx) then
-                for (
-                    ann <- claxx.getAnnotationsByType(CLS_INTENT);
-                    intent <- NCIDLCompiler.compile(ann.value, cfg, 
class2Str(claxx))
-                )
+        def processClassAnnotations(cls: Class[_]): Unit =
+            if cls != null && processed.add(cls) then
+                for (ann <- cls.getAnnotationsByType(CLS_INTENT); intent <- 
NCIDLCompiler.compile(ann.value, cfg, class2Str(cls)))
                     addDecl(intent)
 
-                processClassAnnotations(claxx.getSuperclass)
-                claxx.getInterfaces.foreach(processClassAnnotations)
+                processClassAnnotations(cls.getSuperclass)
+                cls.getInterfaces.foreach(processClassAnnotations)
 
         // First phase scan.
         // For given object finds references via fields (NCIntentObject). 
Scans also each reference recursively and collects them.
@@ -592,21 +553,20 @@ object NCModelScanner extends LazyLogging:
             val refId = ann.value.strip
             val intent = intentDecls.getOrElse(
                 refId,
-                E(s"@NCIntentRef(\"$refId\") references unknown intent ID 
[mdlId=${cfg.getId}, origin=${cfg.getOrigin}, callback=${method2Str(mtd)}]")
+                E(s"$IR(\"$refId\") references unknown intent ID [$z, 
callback=${method2Str(mtd)}]")
             )
 
             addDecl(intent)
             addIntent(intent, mtd, obj)
 
         val unusedIds = intentDecls.keys.filter(k => 
!intents.exists(_.intent.id == k))
-
         if unusedIds.nonEmpty then
-            logger.warn(s"Intents are unused (have no callback): 
[mdlId=${cfg.getId}, origin=${cfg.getOrigin}, intentIds=${col2Str(unusedIds)}]")
+            logger.warn(s"Intents are unused (have no callback): [$z, 
intentIds=${col2Str(unusedIds)}]")
 
         if intents.nonEmpty then
             // Check the uniqueness of intent IDs.
             NCUtils.getDups(intents.map(_.intent.id).toSeq) match
-                case ids if ids.nonEmpty => E(s"Duplicate intent IDs 
[mdlId=${cfg.getId}, origin=${cfg.getOrigin}, ids=${col2Str(ids)}]")
+                case ids if ids.nonEmpty => E(s"Duplicate intent IDs [$z, 
ids=${col2Str(ids)}]")
                 case _ => // No-op.
         else
             logger.warn(s"Model has no intent: ${cfg.getId}")
diff --git 
a/nlpcraft/src/test/scala/org/apache/nlpcraft/internal/intent/compiler/NCIDLCompilerSpec.scala
 
b/nlpcraft/src/test/scala/org/apache/nlpcraft/internal/intent/compiler/NCIDLCompilerSpec.scala
index f4b0d5c..6214697 100644
--- 
a/nlpcraft/src/test/scala/org/apache/nlpcraft/internal/intent/compiler/NCIDLCompilerSpec.scala
+++ 
b/nlpcraft/src/test/scala/org/apache/nlpcraft/internal/intent/compiler/NCIDLCompilerSpec.scala
@@ -299,12 +299,10 @@ class NCIDLCompilerSpec:
         def test0(idl: String): Unit =
             try
                 NCIDLCompiler.compile(idl, CFG, "test-origin")
-
-                require(false)
+                require(true)
             catch
-                case e: NCException => println(s"Expected error: $e")
+                case e: NCException => println(s"Unexpected error: $e")
 
         test0("")
         test0(" ")
-        test0(null)
 

Reply via email to