Skip to content

Commit b6c2609

Browse files
committed
Reduce logging overhead and minor cleanups
1 parent 735033e commit b6c2609

14 files changed

+53
-46
lines changed

src/main/scala/scala/async/internal/AnfTransform.scala

+4-2
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,11 @@ private[async] trait AnfTransform {
3838
indent += 1
3939
def oneLine(s: Any) = s.toString.replaceAll("""\n""", "\\\\n").take(127)
4040
try {
41-
AsyncUtils.trace(s"${indentString}$prefix(${oneLine(args)})")
41+
if(AsyncUtils.trace)
42+
AsyncUtils.trace(s"$indentString$prefix(${oneLine(args)})")
4243
val result = t
43-
AsyncUtils.trace(s"${indentString}= ${oneLine(result)}")
44+
if(AsyncUtils.trace)
45+
AsyncUtils.trace(s"$indentString= ${oneLine(result)}")
4446
result
4547
} finally {
4648
indent -= 1

src/main/scala/scala/async/internal/AsyncAnalysis.scala

+1-3
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55
package scala.async.internal
66

77
import scala.collection.mutable.ListBuffer
8-
import scala.reflect.macros.Context
9-
import scala.collection.mutable
108

119
trait AsyncAnalysis {
1210
self: AsyncMacro =>
@@ -30,7 +28,7 @@ trait AsyncAnalysis {
3028

3129
override def nestedClass(classDef: ClassDef) {
3230
val kind = if (classDef.symbol.asClass.isTrait) "trait" else "class"
33-
reportUnsupportedAwait(classDef, s"nested ${kind}")
31+
reportUnsupportedAwait(classDef, s"nested $kind")
3432
}
3533

3634
override def nestedModule(module: ModuleDef) {

src/main/scala/scala/async/internal/AsyncBase.scala

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ abstract class AsyncBase {
4646
val asyncMacro = AsyncMacro(c, self)(body.tree)
4747

4848
val code = asyncMacro.asyncTransform[T](execContext.tree)(c.weakTypeTag[T])
49-
AsyncUtils.vprintln(s"async state machine transform expands to:\n ${code}")
49+
AsyncUtils.vprintln(s"async state machine transform expands to:\n $code")
5050

5151
// Mark range positions for synthetic code as transparent to allow some wiggle room for overlapping ranges
5252
for (t <- code) t.setPos(t.pos.makeTransparent)

src/main/scala/scala/async/internal/AsyncId.scala

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ object AsyncTestLV extends AsyncBase {
2525

2626
def asyncIdImpl[T: c.WeakTypeTag](c: Context)(body: c.Expr[T]): c.Expr[T] = asyncImpl[T](c)(body)(c.literalUnit)
2727

28-
var log: List[(String, Any)] = List()
28+
var log: List[(String, Any)] = Nil
2929
def assertNulledOut(a: Any): Unit = assert(log.exists(_._2 == a), AsyncTestLV.log)
3030
def assertNotNulledOut(a: Any): Unit = assert(!log.exists(_._2 == a), AsyncTestLV.log)
31-
def clear() = log = Nil
31+
def clear(): Unit = log = Nil
3232

3333
def apply(name: String, v: Any): Unit =
3434
log ::= (name -> v)

src/main/scala/scala/async/internal/AsyncMacro.scala

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ private[async] trait AsyncMacro
2424
val body: c.Tree
2525
var containsAwait: c.Tree => Boolean
2626

27-
lazy val macroPos = c.macroApplication.pos.makeTransparent
28-
def atMacroPos(t: c.Tree) = c.universe.atPos(macroPos)(t)
27+
lazy val macroPos: c.universe.Position = c.macroApplication.pos.makeTransparent
28+
def atMacroPos(t: c.Tree): c.Tree = c.universe.atPos(macroPos)(t)
2929

3030
}

src/main/scala/scala/async/internal/AsyncTransform.scala

+3-2
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,12 @@ trait AsyncTransform {
6666

6767
val stateMachineClass = stateMachine.symbol
6868
val asyncBlock: AsyncBlock = {
69-
val symLookup = new SymLookup(stateMachineClass, applyDefDefDummyBody.vparamss.head.head.symbol)
69+
val symLookup = SymLookup(stateMachineClass, applyDefDefDummyBody.vparamss.head.head.symbol)
7070
buildAsyncBlock(anfTree, symLookup)
7171
}
7272

73-
logDiagnostics(anfTree, asyncBlock.asyncStates.map(_.toString))
73+
if(AsyncUtils.verbose)
74+
logDiagnostics(anfTree, asyncBlock.asyncStates.map(_.toString))
7475

7576
val liftedFields: List[Tree] = liftables(asyncBlock.asyncStates)
7677

src/main/scala/scala/async/internal/AsyncUtils.scala

+5-4
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ package scala.async.internal
55

66
object AsyncUtils {
77

8+
89
private def enabled(level: String) = sys.props.getOrElse(s"scala.async.$level", "false").equalsIgnoreCase("true")
910

10-
private def verbose = enabled("debug")
11-
private def trace = enabled("trace")
11+
private[async] val verbose = enabled("debug")
12+
private[async] val trace = enabled("trace")
1213

13-
private[async] def vprintln(s: => Any): Unit = if (verbose) println(s"[async] $s")
14+
@inline private[async] def vprintln(s: => Any): Unit = if (verbose) println(s"[async] $s")
1415

15-
private[async] def trace(s: => Any): Unit = if (trace) println(s"[async] $s")
16+
@inline private[async] def trace(s: => Any): Unit = if (trace) println(s"[async] $s")
1617
}

src/main/scala/scala/async/internal/ExprBuilder.scala

+3-6
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,7 @@
44
package scala.async.internal
55

66
import scala.collection.mutable.ListBuffer
7-
import collection.mutable
87
import language.existentials
9-
import scala.reflect.api.Universe
10-
import scala.reflect.api
118

129
trait ExprBuilder {
1310
builder: AsyncMacro =>
@@ -370,11 +367,11 @@ trait ExprBuilder {
370367
c.Expr[futureSystem.Prom[T]](symLookup.memberRef(name.result)), lastStateBody)
371368
mkHandlerCase(lastState.state, Block(rhs.tree, Return(literalUnit)))
372369
}
373-
asyncStates.toList match {
370+
asyncStates match {
374371
case s :: Nil =>
375372
List(caseForLastState)
376373
case _ =>
377-
val initCases = for (state <- asyncStates.toList.init) yield state.mkHandlerCaseForState[T]
374+
val initCases = for (state <- asyncStates.init) yield state.mkHandlerCaseForState[T]
378375
initCases :+ caseForLastState
379376
}
380377
}
@@ -442,7 +439,7 @@ trait ExprBuilder {
442439
* }
443440
*/
444441
def onCompleteHandler[T: WeakTypeTag]: Tree = {
445-
val onCompletes = initStates.flatMap(_.mkOnCompleteHandler[T]).toList
442+
val onCompletes = initStates.flatMap(_.mkOnCompleteHandler[T])
446443
forever {
447444
adaptToUnit(toList(resumeFunTree))
448445
}

src/main/scala/scala/async/internal/LiveVariables.scala

+24-16
Original file line numberDiff line numberDiff line change
@@ -63,15 +63,15 @@ trait LiveVariables {
6363
AsyncUtils.vprintln(s"fields never zero-ed out: ${noNull.mkString(", ")}")
6464

6565
/**
66-
* Traverse statements of an `AsyncState`, collect `Ident`-s refering to lifted fields.
66+
* Traverse statements of an `AsyncState`, collect `Ident`-s referring to lifted fields.
6767
*
6868
* @param as a state of an `async` expression
6969
* @return a set of lifted fields that are used within state `as`
7070
*/
7171
def fieldsUsedIn(as: AsyncState): ReferencedFields = {
7272
class FindUseTraverser extends AsyncTraverser {
73-
var usedFields = Set[Symbol]()
74-
var capturedFields = Set[Symbol]()
73+
var usedFields: Set[Symbol] = Set[Symbol]()
74+
var capturedFields: Set[Symbol] = Set[Symbol]()
7575
private def capturing[A](body: => A): A = {
7676
val saved = capturing
7777
try {
@@ -122,7 +122,7 @@ trait LiveVariables {
122122
* A state `i` is contained in the list that is the value to which
123123
* key `j` maps iff control can flow from state `j` to state `i`.
124124
*/
125-
val cfg: Map[Int, List[Int]] = asyncStates.map(as => (as.state -> as.nextStates)).toMap
125+
val cfg: Map[Int, List[Int]] = asyncStates.map(as => as.state -> as.nextStates).toMap
126126

127127
/** Tests if `state1` is a predecessor of `state2`.
128128
*/
@@ -145,8 +145,10 @@ trait LiveVariables {
145145

146146
val finalState = asyncStates.find(as => !asyncStates.exists(other => isPred(as.state, other.state))).get
147147

148-
for (as <- asyncStates)
149-
AsyncUtils.vprintln(s"fields used in state #${as.state}: ${fieldsUsedIn(as)}")
148+
if(AsyncUtils.verbose) {
149+
for (as <- asyncStates)
150+
AsyncUtils.vprintln(s"fields used in state #${as.state}: ${fieldsUsedIn(as)}")
151+
}
150152

151153
/* Backwards data-flow analysis. Computes live variables information at entry and exit
152154
* of each async state.
@@ -201,9 +203,11 @@ trait LiveVariables {
201203
currStates = exitChanged
202204
}
203205

204-
for (as <- asyncStates) {
205-
AsyncUtils.vprintln(s"LVentry at state #${as.state}: ${LVentry(as.state).mkString(", ")}")
206-
AsyncUtils.vprintln(s"LVexit at state #${as.state}: ${LVexit(as.state).mkString(", ")}")
206+
if(AsyncUtils.verbose) {
207+
for (as <- asyncStates) {
208+
AsyncUtils.vprintln(s"LVentry at state #${as.state}: ${LVentry(as.state).mkString(", ")}")
209+
AsyncUtils.vprintln(s"LVexit at state #${as.state}: ${LVexit(as.state).mkString(", ")}")
210+
}
207211
}
208212

209213
def lastUsagesOf(field: Tree, at: AsyncState): Set[Int] = {
@@ -215,7 +219,7 @@ trait LiveVariables {
215219
Set()
216220
}
217221
else LVentry get at.state match {
218-
case Some(fields) if fields.exists(_ == field.symbol) =>
222+
case Some(fields) if fields.contains(field.symbol) =>
219223
Set(at.state)
220224
case _ =>
221225
avoid += at
@@ -228,10 +232,12 @@ trait LiveVariables {
228232
}
229233

230234
val lastUsages: Map[Tree, Set[Int]] =
231-
liftables.map(fld => (fld -> lastUsagesOf(fld, finalState))).toMap
235+
liftables.map(fld => fld -> lastUsagesOf(fld, finalState)).toMap
232236

233-
for ((fld, lastStates) <- lastUsages)
234-
AsyncUtils.vprintln(s"field ${fld.symbol.name} is last used in states ${lastStates.mkString(", ")}")
237+
if(AsyncUtils.verbose) {
238+
for ((fld, lastStates) <- lastUsages)
239+
AsyncUtils.vprintln(s"field ${fld.symbol.name} is last used in states ${lastStates.mkString(", ")}")
240+
}
235241

236242
val nullOutAt: Map[Tree, Set[Int]] =
237243
for ((fld, lastStates) <- lastUsages) yield {
@@ -242,14 +248,16 @@ trait LiveVariables {
242248
val succNums = lastAsyncState.nextStates
243249
// all successor states that are not indirect predecessors
244250
// filter out successor states where the field is live at the entry
245-
succNums.filter(num => !isPred(num, s)).filterNot(num => LVentry(num).exists(_ == fld.symbol))
251+
succNums.filter(num => !isPred(num, s)).filterNot(num => LVentry(num).contains(fld.symbol))
246252
}
247253
}
248254
(fld, killAt)
249255
}
250256

251-
for ((fld, killAt) <- nullOutAt)
252-
AsyncUtils.vprintln(s"field ${fld.symbol.name} should be nulled out in states ${killAt.mkString(", ")}")
257+
if(AsyncUtils.verbose) {
258+
for ((fld, killAt) <- nullOutAt)
259+
AsyncUtils.vprintln(s"field ${fld.symbol.name} should be nulled out in states ${killAt.mkString(", ")}")
260+
}
253261

254262
nullOutAt
255263
}

src/test/scala/scala/async/TreeInterrogation.scala

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ class TreeInterrogation {
1313
@Test
1414
def `a minimal set of vals are lifted to vars`() {
1515
val cm = reflect.runtime.currentMirror
16-
val tb = mkToolbox(s"-cp ${toolboxClasspath}")
16+
val tb = mkToolbox(s"-cp $toolboxClasspath")
1717
val tree = tb.parse(
1818
"""| import _root_.scala.async.internal.AsyncId._
1919
| async {
@@ -49,7 +49,7 @@ class TreeInterrogation {
4949
&& !dd.symbol.asTerm.isAccessor && !dd.symbol.asTerm.isSetter => dd.name
5050
}
5151
}.flatten
52-
defDefs.map(_.decoded.trim).toList mustStartWith (List("foo$macro$", "<init>", "apply", "apply"))
52+
defDefs.map(_.decoded.trim) mustStartWith List("foo$macro$", "<init>", "apply", "apply")
5353
}
5454
}
5555

src/test/scala/scala/async/run/SyncOptimizationSpec.scala

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ class SyncOptimizationSpec {
1010
@Test
1111
def awaitOnCompletedFutureRunsOnSameThread: Unit = {
1212

13-
def stackDepth = Thread.currentThread().getStackTrace.size
13+
def stackDepth = Thread.currentThread().getStackTrace.length
1414

1515
val future = async {
1616
val thread1 = Thread.currentThread

src/test/scala/scala/async/run/anf/AnfTransformSpec.scala

+3-3
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ class AnfTransformSpec {
217217
val result = async {
218218
var i = 0
219219
def next() = {
220-
i += 1;
220+
i += 1
221221
i
222222
}
223223
foo(next(), await(next()))
@@ -298,7 +298,7 @@ class AnfTransformSpec {
298298
val result = async {
299299
var i = 0
300300
def next() = {
301-
i += 1;
301+
i += 1
302302
i
303303
}
304304
foo(b = next(), a = await(next()))
@@ -311,7 +311,7 @@ class AnfTransformSpec {
311311
import AsyncId.{async, await}
312312
var i = 0
313313
def next() = {
314-
i += 1;
314+
i += 1
315315
i
316316
}
317317
def foo(a: Int = next(), b: Int = next()) = (a, b)

src/test/scala/scala/async/run/ifelse4/IfElse4.scala

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ class IfElse4Spec {
5656
@Test
5757
def `await result with complex type containing skolem`() {
5858
val o = new TestIfElse4Class
59-
val fut = o.run(new o.K(null))
59+
val fut = o.run(o.K(null))
6060
val res = Await.result(fut, 2 seconds)
6161
res.id mustBe ("foo")
6262
}

src/test/scala/scala/async/run/match0/Match0.scala

+1-1
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ class MatchSpec {
7373
val x = 1
7474
Option(x) match {
7575
case op @ Some(x) =>
76-
assert(op == Some(1))
76+
assert(op.contains(1))
7777
x + AsyncId.await(x)
7878
case None => AsyncId.await(0)
7979
}

0 commit comments

Comments
 (0)