0

I´m using Macros, and I would like to check in compilation time, if an instance class created contains all attribute passed in the constructor, or if one of them are null, and if that's the case fail in compilation time instead in runtime.

I´ve been reading a lot of blogs about it and I found none regarding this particular scenario, so maybe is not doable in compilation time.

If it's possible and someone know a blog, paper to read about how to do it with AST I would appreciate.

Here my builder class

actorBuilder = F2eActorBuilder
  .withApplicationConf(new File(applicationContext))
  .withAkkaContext( "akkaContext.xml")
  .withApplicationContext("applicationContext.xml")
  .build()

I want to check actorBuilder once is defined, and since is a DSL and some with* might not being invoked I want to check in compilation time if one of those attributes are set as null.

And here my Macro code

  import scala.language.experimental.macros

  def valid(action: F2eActorBuilder): F2eActorBuilder = macro checkActionImpl

  def checkActionImpl(c: blackbox.Context)(action: c.Tree): c.Tree = {
    import c.universe._
    def isValidAction(s: F2eActorBuilder): Boolean = checkMessage(s)

    action match {
      case _tree@Literal(Constant(s: F2eActorBuilder)) if isValidAction(s) => _tree
      case _tree@Literal(Constant(s: F2eActorBuilder)) => c.abort(c.enclosingPosition, getErrorMessage(s))
    }
  }

  def checkMessage(action: F2eActorBuilder): Boolean = {
    action.akkaContextPath != null
  }

  def getErrorMessage(action: F2eActorBuilder): String = {
    s"Some mandatory attributes are marked as null"
  }
paul
  • 12,873
  • 23
  • 91
  • 153
  • Please give more detailed example of what you're trying to do. – ghik Jun 25 '18 at 12:37
  • Hi, I already did, take a look to see if it has sense to you, also I will paste my macro code – paul Jun 25 '18 at 12:40
  • In general case what you ask is impossible, because you can only guard against explicitly passed null literal - something that can be easier achieved by usage of linters like wartremovers. However, if you passed the parameter from somewhere: as a parameters, or some computation's result, you will not be able to validate it without validating all paths the code can take. Basically, as long as language allows null you cannot completely get rid of it at compile time. – Mateusz Kubuszok Jun 25 '18 at 15:27

0 Answers0