Giter VIP home page Giter VIP logo

scala-nameof's Introduction

"nameOf" macro for scala

Build Maven Central javadoc

Get the name of an variable, function, class member, or type as a string--at compile-time!

Inspired by the nameof operator in C#

Used to obtain the simple (unqualified) string name of a variable, type, or member. When reporting errors in code, hooking up model-view-controller (MVC) links, firing property changed events, etc., you often want to capture the string name of a method. Using nameof helps keep your code valid when renaming definitions. Before you had to use string literals to refer to definitions, which is brittle when renaming code elements because tools do not know to check these string literals.

Usage

Add the library as "provided", because it's only needed during compilation and not at runtime:

libraryDependencies += "com.github.dwickern" %% "scala-nameof" % "4.0.0" % "provided"

And import the package:

import com.github.dwickern.macros.NameOf._

Now you can use nameOf to get the name of a variable or class member:

case class Person(name: String, age: Int)

def toMap(person: Person) = Map(
  nameOf(person.name) -> person.name,
  nameOf(person.age) -> person.age
)
// compiles to:

def toMap(person: Person) = Map(
  "name" -> person.name,
  "age" -> person.age
)

To get the name of a function:

def startCalculation(value: Int): Unit = {
  println("Entered " + nameOf(startCalculation _))
}
// compiles to:

def startCalculation(value: Int): Unit = {
  println("Entered startCalculation")
}

Without having an instance of the type:

case class Person(name: String, age: Int) {
  def sayHello(other: Person) = s"Hello ${other.name}!"
}

println(nameOf[Person](_.age))
println(nameOf[Person](_.sayHello(???)))
// compiles to:

println("age")
println("sayHello")

You can also use nameOfType to get the unqualified name of a type:

println(nameOfType[java.lang.String])
// compiles to:

println("String")

And qualifiedNameOfType to get the qualified name:

println(qualifiedNameOfType[java.lang.String])
// compiles to:

println("java.lang.String")

Development

To run tests for all compilation targets:

sbt +test

To publish to your local ivy repository:

sbt +publishLocal

To publish to maven central (requires authorization):

sbt release

License

See LICENSE (MIT).

scala-nameof's People

Contributors

dwickern avatar funfunfine avatar johnspaul avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

scala-nameof's Issues

object dwickern is not a member of package com.github

i can't find out why

import com.github.dwickern.macros.NameOf._

leads to

Abc.scala:17:12: object dwickern is not a member of package com.github [17:12]

In build.sbt i've added

libraryDependencies += "com.github.dwickern" %% "scala-nameof" % "3.0.0" % "provided"

Any ideas?

doesn't work for Java compile-time constants

public class JavaConstants {
    public static final int FOO = 42;
}
nameOf(JavaConstants.FOO) // compile error

The identifier is replaced with the constant value 42 before the macro evaluates.

anonymous types support, i.e.: `new js.Object {}`

how can nameOf be made to work for anonymous new js.Object{}:

val mutations = new js.Object {
    def increment(state: State) = state.count+=1
    def decrement(state: State) = state.count-=1
}

// Error: " value increment is not a member of scala.scalajs.js.Object"

val name = nameOf(mutations.increment _) 

Scala.js in v4.0.0

Thanks for this great library.
I noticed that release v4.0.0 doesn't support Scala.js anymore. Is there a specific reason for this?

Scala 3

Hi, thanks for this very useful lib.

Do you plan to do a Scala 3 version ?

Can I use nameOf[T](function) to get the field name

Thanks for your awesome work.

I have a problem using nameof without having an instance of the type.

We can use the following way to get a field name

case class Person(name: String, age: Int)

println(nameOf((_:Person).age)) // age
println(nameOf[Person](_.age)) // age

But if I make (_:Person).age to a parameter, so we only get the parameter name, how can i get the real field name according the function:

val foo = (_:Person).age
println(nameOf(foo)) // foo, but I want age
println(nameOf[Person](foo)) // foo, but I want age

Thanks

Compile time whitebox macro returns a type that is too wide

Demo:

  import shapeless.syntax.singleton._
  import shapeless.record._

  it("can get name singleton") {

    val t1 = NameOf.nameOfType[Seq[Int]]

    val record = (t1 ->> "r") :: "a" ->> 5 :: HNil

    val r = record.apply("Seq")

    println(r)
  }

which compiles to the following error:

[Error] /home/peng/git/shapesafe/core/src/test/scala/org/shapesafe/core/debugging/InfoCTSpec.scala:19: No field String("Seq") in record String with shapeless.labelled.KeyTag[t1.type,String] :: Int with shapeless.labelled.KeyTag[String("a"),Int] :: shapeless.HNil
one error found

This doesn't use the full potential of the macro, as t1 can be assigned a singleton type "Seq" in scala 2.13, or a witnessed type in scala < 2.13 using shapeless

The following works however in scala 2.13, not sure how:

  import shapeless.syntax.singleton._
  import shapeless.record._

  it("can get name singleton") {

    val t1: "Seq" = NameOf.nameOfType[Seq[Int]]

    val record = (t1 ->> "r") :: "a" ->> 5 :: HNil

    val r = record.apply("Seq")

    println(r)
  }

current reflection api

consider switching to current reflection api, to remove build warnings (scala 2.12)


import scala.reflect.macros.whitebox._

object NameOfImpl {

  def nameOf( ctx : Context )( expr : ctx.Expr[ Any ] ) : ctx.Expr[ String ] = {
    import ctx.universe._

    @tailrec
    def extract( tree : ctx.Tree ) : ctx.Name = tree match {
      case Ident( n )           => n
      case Select( _, n )       => n
      case Function( _, body )  => extract( body )
      case Block( _, expr )     => extract( expr )
      case Apply( func, _ )     => extract( func )
      case TypeApply( func, _ ) => extract( func )
      case _                    => ctx.abort( ctx.enclosingPosition, s"Unsupported expression: $expr" )
    }

    val name = extract( expr.tree ).decodedName.toString()

    ctx.Expr[String]( q"$name" )

  }

  def nameOfType[ T ]( ctx : Context )( implicit tag : ctx.WeakTypeTag[ T ] ) : ctx.Expr[ String ] = {
    import ctx.universe._

    val name = showRaw( tag.tpe.typeSymbol.name )

    ctx.Expr[String]( q"$name" )

  }

  def qualifiedNameOfType[ T ]( ctx : Context )( implicit tag : ctx.WeakTypeTag[ T ] ) : ctx.Expr[ String ] = {
    import ctx.universe._

    val name = showRaw( tag.tpe.typeSymbol.fullName )

    ctx.Expr[String]( q"$name" )

  }

}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.