scala.language.dynamics Scala Examples
The following examples show how to use scala.language.dynamics.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: Builder.scala From outwatch with Apache License 2.0 | 5 votes |
package outwatch.helpers import outwatch._ import colibri.{Source, Observable} import scala.language.dynamics trait AttributeBuilder[-T, +A <: VDomModifier] extends Any { def assign(value: T): A @inline def :=(value: T): A = assign(value) def :=?(value: Option[T]): Option[A] = value.map(assign) def <--[F[_] : Source](source: F[_ <: T]): VDomModifier = VDomModifier(Observable.map(source)(assign)) } object AttributeBuilder { @inline implicit def toAttribute[A <: VDomModifier](builder: AttributeBuilder[Boolean, A]): A = builder := true } // Attr @inline final class BasicAttrBuilder[T](val name: String, val encode: T => Attr.Value) extends AttributeBuilder[T, BasicAttr] { def assign(value: T) = BasicAttr(name, encode(value)) @inline def accum(s: String): AccumAttrBuilder[T] = accum((v1, v2) => v1.toString + s + v2.toString) @inline def accum(reducer: (Attr.Value, Attr.Value) => Attr.Value) = new AccumAttrBuilder[T](name, encode, reducer) } @inline final class DynamicAttrBuilder[T](val name: String) extends Dynamic with AttributeBuilder[T, BasicAttr] { @inline def selectDynamic(s: String) = new DynamicAttrBuilder[T](name + "-" + s) @inline def assign(value: T) = BasicAttr(name, value.toString) @inline def accum(s: String): AccumAttrBuilder[T] = accum((v1, v2) => v1.toString + s + v2.toString) @inline def accum(reducer: (Attr.Value, Attr.Value) => Attr.Value) = new AccumAttrBuilder[T](name, _.toString, reducer) } @inline final class AccumAttrBuilder[T]( val name: String, encode: T => Attr.Value, reduce: (Attr.Value, Attr.Value) => Attr.Value ) extends AttributeBuilder[T, AccumAttr] { def assign(value: T) = AccumAttr(name, encode(value), reduce) } // Props @inline final class PropBuilder[T](val name: String, encode: T => Prop.Value) extends AttributeBuilder[T, Prop] { def assign(value: T) = Prop(name, encode(value)) } // Styles @inline final class BasicStyleBuilder[T](val name: String) extends AnyVal with AttributeBuilder[T, BasicStyle] { @inline def assign(value: T) = BasicStyle(name, value.toString) @inline def delayed: DelayedStyleBuilder[T] = new DelayedStyleBuilder[T](name) @inline def remove: RemoveStyleBuilder[T] = new RemoveStyleBuilder[T](name) @inline def destroy: DestroyStyleBuilder[T] = new DestroyStyleBuilder[T](name) @inline def accum: AccumStyleBuilder[T] = accum(",") @inline def accum(s: String): AccumStyleBuilder[T] = accum(_ + s + _) @inline def accum(reducer: (String, String) => String) = new AccumStyleBuilder[T](name, reducer) } @inline final class DelayedStyleBuilder[T](val name: String) extends AnyVal with AttributeBuilder[T, DelayedStyle] { @inline def assign(value: T) = DelayedStyle(name, value.toString) } @inline final class RemoveStyleBuilder[T](val name: String) extends AnyVal with AttributeBuilder[T, RemoveStyle] { @inline def assign(value: T) = RemoveStyle(name, value.toString) } @inline final class DestroyStyleBuilder[T](val name: String) extends AnyVal with AttributeBuilder[T, DestroyStyle] { @inline def assign(value: T) = DestroyStyle(name, value.toString) } @inline final class AccumStyleBuilder[T](val name: String, reducer: (String, String) => String) extends AttributeBuilder[T, AccumStyle] { def assign(value: T) = AccumStyle(name, value.toString, reducer) } object KeyBuilder { @inline def assign(key: Key.Value): Key = Key(key) @inline def :=(key: Key.Value): Key = assign(key) }
Example 2
Source File: singletons.scala From iota with Apache License 2.0 | 5 votes |
package iota //#=cats package iotaz //#=scalaz package test import scala.language.dynamics import scala.reflect.macros.whitebox.Context import scala.Predef.augmentString trait Literal { type T } object Literal { type Bound[A] = Literal { type T <: A } } object LiteralInt extends Dynamic { def selectDynamic(selector: String): Literal.Bound[Int] = macro MacrosLiterally.literalIntSelectDynamic } object LiteralString extends Dynamic { def selectDynamic(selector: String): Literal.Bound[String] = macro MacrosLiterally.literalStringSelectDynamic } final class MacrosLiterally(val c: Context) { import c.universe.{ Literal => ASTLiteral, _ } import internal.decorators._ private[this] final val iotaPackage: Tree = q"_root_.iota" //#=cats q"_root_.iotaz" //#=scalaz def literalIntSelectDynamic(selector: Tree): Tree = { val q"${value: String}" = selector val tpe = c.internal.constantType(Constant(value.toInt)) val tree = tq"$iotaPackage.test.Literal { type T = $tpe }" ASTLiteral(Constant(())).setType(c.typecheck(tree, mode = c.TYPEmode).tpe) } def literalStringSelectDynamic(selector: Tree): Tree = { val q"${value: String}" = selector val tpe = c.internal.constantType(Constant(value)) val tree = tq"$iotaPackage.test.Literal { type T = $tpe }" ASTLiteral(Constant(())).setType(c.typecheck(tree, mode = c.TYPEmode).tpe) } }
Example 3
Source File: unions.scala From perf_tester with Apache License 2.0 | 5 votes |
package shapeless import scala.language.dynamics import scala.language.experimental.macros import scala.reflect.macros.whitebox object union { import syntax.UnionOps implicit def unionOps[C <: Coproduct](u : C) : UnionOps[C] = new UnionOps(u) object Union extends Dynamic { def applyDynamicNamed[U <: Coproduct](method: String)(elems: Any*): U = macro UnionMacros.mkUnionNamedImpl[U] def selectDynamic(tpeSelector: String): Any = macro LabelledMacros.unionTypeImpl } } @macrocompat.bundle class UnionMacros(val c: whitebox.Context) { import c.universe._ import internal.constantType import labelled.FieldType val fieldTypeTpe = typeOf[FieldType[_, _]].typeConstructor val SymTpe = typeOf[scala.Symbol] val atatTpe = typeOf[tag.@@[_,_]].typeConstructor def mkUnionNamedImpl[U <: Coproduct : WeakTypeTag](method: Tree)(elems: Tree*): Tree = { def mkSingletonSymbolType(c: Constant): Type = appliedType(atatTpe, List(SymTpe, constantType(c))) def mkFieldTpe(keyTpe: Type, valueTpe: Type): Type = appliedType(fieldTypeTpe, List(keyTpe, valueTpe.widen)) def mkElem(keyTpe: Type, value: Tree): Tree = q"$value.asInstanceOf[${mkFieldTpe(keyTpe, value.tpe)}]" def promoteElem(elem: Tree): Tree = elem match { case q""" $prefix(${Literal(k: Constant)}, $v) """ => mkElem(mkSingletonSymbolType(k), v) case _ => c.abort(c.enclosingPosition, s"$elem has the wrong shape for a record field") } val q"${methodString: String}" = method if(methodString != "apply") c.abort(c.enclosingPosition, s"this method must be called as 'apply' not '$methodString'") val elem = elems match { case Seq(e) => e case _ => c.abort(c.enclosingPosition, s"only one branch of a union may be inhabited") } q""" _root_.shapeless.Coproduct[${weakTypeOf[U]}](${promoteElem(elem)}) """ } }
Example 4
Source File: MagicManager.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.magic import org.apache.toree.plugins.{Plugin, PluginMethodResult, PluginManager} import org.slf4j.LoggerFactory import scala.annotation.tailrec import scala.language.dynamics import scala.runtime.BoxedUnit import scala.util.{Try, Failure, Success} class MagicManager(private val pluginManager: PluginManager) extends Dynamic { protected val logger = LoggerFactory.getLogger(this.getClass.getName) @throws[MagicNotFoundException] def findMagic(name: String): Magic = { @tailrec def inheritsMagic(klass: Class[_]): Boolean = { if (klass == null) false else if (klass.getInterfaces.exists(classOf[Magic].isAssignableFrom)) true else inheritsMagic(klass.getSuperclass) } val magics = pluginManager.plugins .filter(p => inheritsMagic(p.getClass)) .filter(_.simpleName.split("\\.").last.toLowerCase == name.toLowerCase) if (magics.size <= 0){ logger.error(s"No magic found for $name!") throw new MagicNotFoundException(name) } else if (magics.size > 1) { logger.warn(s"More than one magic found for $name!") } magics.head.asInstanceOf[Magic] } @throws[MagicNotFoundException] def applyDynamic(name: String)(args: Any*): MagicOutput = { val arg = args.headOption.map(_.toString).getOrElse("") import org.apache.toree.plugins.Implicits._ val result = pluginManager.fireEventFirstResult( name.toLowerCase(), "input" -> arg ) result match { case Some(r: PluginMethodResult) => handleMagicResult(name, r.toTry) case None => throw new MagicNotFoundException(name) } } private def handleMagicResult(name: String, result: Try[Any]): MagicOutput = result match { case Success(magicOutput) => magicOutput match { case out: MagicOutput => out case null | _: BoxedUnit => MagicOutput() case cmo: Map[_, _] if cmo.keys.forall(_.isInstanceOf[String]) && cmo.values.forall(_.isInstanceOf[String]) => MagicOutput(cmo.asInstanceOf[Map[String, String]].toSeq:_*) case unknown => val message = s"""Magic $name did not return proper magic output |type. Expected ${classOf[MagicOutput].getName}, but found |type of ${unknown.getClass.getName}.""".trim.stripMargin logger.warn(message) MagicOutput("text/plain" -> message) } case Failure(t) => val message = s"Magic $name failed to execute with error: \n${t.getMessage}" logger.warn(message, t) MagicOutput("text/plain" -> message) } }
Example 5
package me.shadaj.scalapy.py import scala.language.dynamics import scala.collection.mutable trait Any extends scala.Any { self => private[py] def value: PyValue final def expr: VariableReference = { CPythonInterpreter.getVariableReference(value) } override def toString: String = value.getStringified final def as[T: Reader]: T = implicitly[Reader[T]].read(value) } object Any { def populateWith(v: PyValue): Any = { new Any { val value = v } } implicit def from[T](v: T)(implicit writer: Writer[T]): Any = { Any.populateWith(writer.write(v)) } }
Example 6
Source File: Global.scala From scalapy with MIT License | 5 votes |
package me.shadaj.scalapy.py import scala.language.dynamics object global extends scala.Dynamic { def applyDynamic(method: String)(params: Any*): Dynamic = { Any.populateWith(CPythonInterpreter.callGlobal(method, params.map(_.value))).as[Dynamic] } def applyDynamicNamed(method: String)(params: (String, Any)*): Dynamic = { eval(s"$method(${params.map{ case (name, value) => if (name.isEmpty) Arg(value) else Arg(name, value) // Positional arguments have no name }.mkString(",")})") } def selectDynamic(value: String): Any = { Any.populateWith(CPythonInterpreter.selectGlobal(value)) } }
Example 7
Source File: Dynamic.scala From scalapy with MIT License | 5 votes |
package me.shadaj.scalapy.py import scala.language.dynamics @native trait Dynamic extends Any with AnyDynamics trait AnyDynamics extends scala.Any with Any with scala.Dynamic { def applyDynamic(method: String)(params: Any*): Dynamic = { Any.populateWith(CPythonInterpreter.call(value, method, params.map(_.value))).as[Dynamic] } def applyDynamicNamed(method: String)(params: (String, Any)*): Dynamic = { eval(s"${this.expr}.$method(${params.map{ case (name, value) => if (name.isEmpty) Arg(value) else Arg(name, value) // Positional arguments have no name }.mkString(",")})") } def selectDynamic(term: String): Dynamic = { Any.populateWith(CPythonInterpreter.select(value, term)).as[Dynamic] } def updateDynamic(name: String)(newValue: Any): Unit = { CPythonInterpreter.update(value, name, newValue.value) } def arrayAccess(index: Int): Dynamic = { Any.populateWith(CPythonInterpreter.selectList(value, index)).as[Dynamic] } def dictionaryAccess(key: Any): Dynamic = { Any.populateWith(CPythonInterpreter.selectDictionary(value, key.value)).as[Dynamic] } def unary_+(): Dynamic = { Any.populateWith(CPythonInterpreter.unaryPos(value)).as[Dynamic] } def unary_-(): Dynamic = { Any.populateWith(CPythonInterpreter.unaryNeg(value)).as[Dynamic] } def +(that: Any): Dynamic = { Any.populateWith(CPythonInterpreter.binaryAdd(value, that.value)).as[Dynamic] } def -(that: Any): Dynamic = { Any.populateWith(CPythonInterpreter.binarySub(value, that.value)).as[Dynamic] } def *(that: Any): Dynamic = { Any.populateWith(CPythonInterpreter.binaryMul(value, that.value)).as[Dynamic] } def /(that: Any): Dynamic = { Any.populateWith(CPythonInterpreter.binaryDiv(value, that.value)).as[Dynamic] } def %(that: Any): Dynamic = { Any.populateWith(CPythonInterpreter.binaryMod(value, that.value)).as[Dynamic] } }
Example 8
Source File: Visualization.scala From lightning-scala with MIT License | 5 votes |
package org.viz.lightning import org.json4s.DefaultFormats import org.json4s.native.Serialization import scala.language.dynamics import scalaj.http._ class Visualization(val lgn: Lightning, val id: String, val name: String) { if (lgn.isNotebook) { //implicit val HTMLViz = org.refptr.iscala.display.HTMLDisplay[Visualization] { viz => // viz.getHTML //} //org.refptr.iscala.display.display_html(this) } def formatURL(url: String): String = { val out = url.last.toString match { case "/" => url case _ => url + "/" } out + "?host=" + lgn.host } def getPermalinkURL: String = { lgn.host + "/visualizations/" + id } def getEmbedLink: String = { formatURL(this.getPermalinkURL + "/embed") } def getIframeLink: String = { formatURL(this.getPermalinkURL + "/iframe") } def getPymLink: String = { formatURL(this.getPermalinkURL + "/pym") } def getDataLink: String = { formatURL(lgn.host + "/sessions/" + lgn.session + "/visualizations/" + id + "/data/") } def getHTML: String = { val url = getEmbedLink var request = Http(url).method("GET") if (lgn.auth.nonEmpty) { request = request.auth(lgn.auth.get._1, lgn.auth.get._2) } request.asString.body } def append(payload: Map[String, Any]) : Visualization = { val url = lgn.host + "/sessions/" + lgn.session + "/visualizations/" + this.id + "/data/" implicit val formats = DefaultFormats val blob = Map("data" -> payload) lgn.post(url, Serialization.write(blob)) this } def getPublicLink: String = { this.getPermalinkURL + "/public/" } }
Example 9
Source File: PythonFunction.scala From polynote with Apache License 2.0 | 5 votes |
package polynote.runtime.python import java.util.concurrent.{Callable, ExecutorService} import jep.python.PyCallable import shapeless.Witness import scala.collection.JavaConverters._ import scala.language.dynamics class PythonFunction(callable: PyCallable, runner: PythonObject.Runner) extends TypedPythonObject[PythonFunction.function](callable, runner) with Dynamic { private def unwrapArg(arg: Any): Any = arg match { case pyObj: PythonObject => pyObj.unwrap case obj => obj } override def applyDynamic(method: String)(args: Any*): PythonObject = { if (method == "apply" || method == "call" || method == "__call__") callPosArgs(callable, args.asInstanceOf[Seq[AnyRef]]) else super.applyDynamic(method)(args: _*) } override def applyDynamicNamed(method: String)(args: (String, Any)*): PythonObject = { if (method == "apply" || method == "call" || method == "__call__") callKwArgs(callable, args) else super.applyDynamicNamed(method)(args: _*) } } object PythonFunction { type function = Witness.`"function"`.T }
Example 10
Source File: MagicManager.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.magic import org.apache.toree.plugins.{Plugin, PluginMethodResult, PluginManager} import org.slf4j.LoggerFactory import scala.annotation.tailrec import scala.language.dynamics import scala.runtime.BoxedUnit import scala.util.{Try, Failure, Success} class MagicManager(private val pluginManager: PluginManager) extends Dynamic { protected val logger = LoggerFactory.getLogger(this.getClass.getName) @throws[MagicNotFoundException] def findMagic(name: String): Magic = { @tailrec def inheritsMagic(klass: Class[_]): Boolean = { if (klass == null) false else if (klass.getInterfaces.exists(classOf[Magic].isAssignableFrom)) true else inheritsMagic(klass.getSuperclass) } val magics = pluginManager.plugins .filter(p => inheritsMagic(p.getClass)) .filter(_.simpleName.split("\\.").last.toLowerCase == name.toLowerCase) if (magics.size <= 0){ logger.error(s"No magic found for $name!") throw new MagicNotFoundException(name) } else if (magics.size > 1) { logger.warn(s"More than one magic found for $name!") } magics.head.asInstanceOf[Magic] } @throws[MagicNotFoundException] def applyDynamic(name: String)(args: Any*): MagicOutput = { val arg = args.headOption.map(_.toString).getOrElse("") import org.apache.toree.plugins.Implicits._ val result = pluginManager.fireEventFirstResult( name.toLowerCase(), "input" -> arg ) result match { case Some(r: PluginMethodResult) => handleMagicResult(name, r.toTry) case None => throw new MagicNotFoundException(name) } } private def handleMagicResult(name: String, result: Try[Any]): MagicOutput = result match { case Success(magicOutput) => magicOutput match { case out: MagicOutput => out case null | _: BoxedUnit => MagicOutput() case cmo: Map[_, _] if cmo.keys.forall(_.isInstanceOf[String]) && cmo.values.forall(_.isInstanceOf[String]) => MagicOutput(cmo.asInstanceOf[Map[String, String]].toSeq:_*) case unknown => val message = s"""Magic $name did not return proper magic output |type. Expected ${classOf[MagicOutput].getName}, but found |type of ${unknown.getClass.getName}.""".trim.stripMargin logger.warn(message) MagicOutput("text/plain" -> message) } case Failure(t) => val message = s"Magic $name failed to execute with error: \n${t.getMessage}" logger.warn(message, t) MagicOutput("text/plain" -> message) } }
Example 11
Source File: ParamMaker.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.macros import ru.tinkoff.tschema.macros.ParamMaker.Applyer import ru.tinkoff.tschema.typeDSL import ru.tinkoff.tschema.typeDSL.{Capture, DSLAtom, FormField, Header, QueryParam} import scala.language.{dynamics, higherKinds} import scala.language.experimental.macros import shapeless.Witness import scala.reflect.macros.whitebox class ParamMaker[T[_, _]] extends Dynamic { def params[A]: Applyer = macro ParamMakerMacro.paramsImpl[A, T[_, _]] } object ParamMaker { type Applyer = { def apply[A](x: => A): DSLAtom } def apply[T[_, _]]: ParamMaker[T] = new ParamMaker[T] object query extends ParamMaker[QueryParam] object path extends ParamMaker[Capture] object headers extends ParamMaker[Header] object form extends ParamMaker[FormField] } class ParamMakerMacro(val c: whitebox.Context) extends SymbolMacros { import c.universe._ val consTpe = typeOf[typeDSL.:>[_, _]].typeConstructor def paramsImpl[A: WeakTypeTag, T: WeakTypeTag] = { val const = weakTypeTag[T].tpe.typeConstructor val result = extractNamesTypes(weakTypeOf[A]).map { case (name, tpe) => appliedType(const, KeyName(name), tpe) } .reduce((a, b) => appliedType(consTpe, a, b)) q""" new { import ru.tinkoff.tschema.typeDSL.{:>} def apply[A](x: => A): :>[$result, A] = new :> }""" } def extractNamesTypes(ref: Type): List[(String, Type)] = ref match { case RefinedType(tpes, scope) => info(tpes) scope.collect { case m: MethodSymbol => info(m) m.name.decodedName.toString -> m.returnType }.toList case _ => List.empty } def info[A](mess: A) = c.info(c.enclosingPosition, mess.toString, force = false) }