Variable scope in Stylus - module

How stylus deals with variables scope?
--
1- Are all variables global?
$foo = red // is $foo global?
2- Similarly to the commonJS module, is there any exports/require equivalent?
$foo = #import 'foo'
body { color: $foo }
3- What about variables declared in a CSS block, maybe with mixins:
$foo = green
bar()
$foo = yellow // is it the same $foo ?
$baz = blue. // local or implied global?
ul {
background: $foo // green or yellow? red?
$foo = red
li {
$foo = pink
}
color: $foo // pink?
bar() // what about $foo now?
}
--
Would appreciate any clarification or documentation about this...
Thank you

If you slightly reword part #3 of your question:
$foo = green
p('global: $foo is ' $foo)
bar()
$foo = yellow
p('In bar(): $foo is ' $foo)
$baz = blue
p('$baz outside of bar() is ' $baz)
ul {
background: $foo
p('In ul: $foo is ' $foo)
$foo = red
p('In ul: now $foo is ' $foo)
li {
$foo = pink
p('In ul li: $foo is ' $foo)
}
color: $foo // pink?
p('Back in ul: now $foo is ' $foo)
bar()
p('what about $foo now? ' $foo)
}
Then stylus will answer it:
$ stylus test.styl
inspect: 'global: $foo is ' (#008000)
inspect: '$baz outside of bar() is ' $baz
inspect: 'In ul: $foo is ' (#008000)
inspect: 'In ul: now $foo is ' (#f00)
inspect: 'In ul li: $foo is ' (#ffc0cb)
inspect: 'Back in ul: now $foo is ' (#f00)
inspect: 'In bar(): $foo is ' (#ff0)
inspect: 'what about $foo now? ' (#f00)
compiled test.css

Related

Kotlin companion object unexpected result

sealed class Color () {
sealed class Dark (): Color() {
object DarkRed : Dark()
object DarkBlue : Dark()
}
override fun toString(): String = when (this) {
is Color.Dark -> "Dark"
is Color.Dark.DarkRed -> "Dark Red"
is Color.Dark.DarkBlue -> "Dark Blue"
}
companion object Companion {
fun make(name: String): Color = when (name) {
"DarkRed" -> Color.Dark.DarkRed
"DarkBlue" -> Color.Dark.DarkBlue
else -> throw Exception ("Error unkown color '$name'")
}
}
}
fun main(args: Array<String>) {
val color = Color.Companion.make("DarkRed")
println (color.toString()) // Dark is printed not "Dark Red"
}
The code above prints Dark while I expected Dark Red. It seems that the make returned type Color.Dark.DarkRed is interpreted as Color.Dark by the ofString() function, why ?
Because 'DarkRed' is both Dark and DarkRed, and is Dark is checked before is DarkRed.
when will enter the first clause that resolves to true.
To fix this put the most specific checks before the lesser specific checks.
You can just put line is Color.Dark -> "Dark" in the end of toString function. In your case is Color.Dark returns true for DarkRed.

Why does a member function invocation not infer a required receiver from the calling function?

Consider:
class Foo {
fun CoroutineScope.foo() {
}
}
class Bar {
val f = Foo()
fun CoroutineScope.bar() { // this could also be "suspend fun bar = coroutineScope {"
f.foo() // unresolved reference
with (f) {
foo() // OK
}
with (f) {
with(this) {
foo() // OK
}
}
}
}
It seems like the first attempt at f.foo() should infer the CoroutineScope receiver specified on bar(). It seems it doesn't; but in an attempt to understand receivers better, does anyone have an explanation as to why?
Edit
(Playground link)
After looking over some docs (specifically the "Declaring extensions as members") and Rene's response, I tried a few more things:
import kotlinx.coroutines.*
class Foo {
fun CoroutineScope.foo() { println("Foo.foo")}
fun Baz.fed(){ println("Foo.fed") }
}
class Baz {
fun CoroutineScope.foo() { println("Baz.foo") }
fun Foo.fed(){ println("Baz.fed") }
}
fun CoroutineScope.foo() { println("CoroutineScope.foo") }
fun foo() { println("Global.foo") }
fun bar(scope: CoroutineScope) {
val f = Foo()
val b = Baz()
println ("Test 1")
foo() // foo() from Global
scope.foo() // foo() from CoroutineScope
//f.foo() // unresolved reference
println ("\nTest 2")
with(scope) {
foo() // foo() from CoroutineScope
//f.foo() // unresolved reference
}
println ("\nTest 3")
with(f) {
scope.foo() // foo() from Foo
foo() // foo() from Global
}
println ("\nTest 4")
with(scope) {
with (f) {
foo() // foo() from Foo
scope.foo() // foo() from Foo
}
}
println ("\nTest 5")
with(f) {
with (scope) {
foo() // foo() from Foo
scope.foo() // foo() from Foo
}
}
println ("\nTest 6")
with(b) {
with(f) {
with (scope) {
foo() // foo() from Foo
fed() // fed() from Baz
}
}
}
println ("\nTest 7")
with(f) {
with(b) {
with (scope) {
foo() // foo() from Baz
fed() // fed() from Foo
}
}
}
}
fun main() = runBlocking {
bar(this)
}
It's interesting to see that when both contexts are made available via with, it is able to figure out which one is the dispatch context and which the extension context, regardless of what order they are provided. But if you specify the extension context directly like f.bar(), it will only look for versions of bar with extension receiver of type Foo, or a direct member of Foo (I'm still a bit hazy about how it views dispatch and extension receivers for a function that is simply defined in the class definition). So it seems the logic is something like:
Given expression x.y():
Find all functions y() that take extension receiver x
For each receiver available c, starting with the most recently added, choose the first x.y() that explicitly takes a dispatch receiver of type c - note that fun CoroutineScope.foo() in global scope acts like it has no dispatch receiver, since tests 6 and 7 show that even though scope is added to the available context list last, Foo (or Baz) version of foo() is used.
Given expression y():
Try to find an x.y() with both a dispatch receiver and extension receiver (x) defined and in the list of available contexts. (note: it chooses the most recently added extension receiver first, then tries to find a matching dispatch receiver (see test 6 and 7 with fed())
If #1 returned nothing, choose most recently added context with dispatch receiver x in available contexts that define function y()
Still nothing? Choose the most recently added context with extension receiver x that define function y()
Fall back to global version of y()
Your declaration:
class Foo {
fun CoroutineScope.foo() {
}
}
defines an extension function foo of CoroutineScope in the context of an instance of the class Foo. This means you can only invoke foo on an instance of CoroutineScope if you are in a scope where this is of the type Foo.
The first attempt f.foo() does exactly the opposite. You invoke foo() on an instance of Foo and this references a CoroutineScope.
The two other examples uses with to set the this reference to Foo and therefor you can invoke foo on the outer CoroutineScope instance.
BTW: with(this) makes no sense, because this will be set to this.

Create a function in Kotlin that takes an enum parameter

I'm creating a function that takes an enum value as a parameter, but I am very new to Kotlin and I can't find any material that covers this specifically.
Example:
enum class Color(val rgb: Int) {
RED(0xFF0000),
ORANGE(0xffa500),
YELLOW(0xffff00),
GREEN(0x00FF00),
BLUE(0x0000FF),
INDIGO(0x4b0082),
VIOLET(0x8F5E99)
}
fun getHexColor (Color: Enum)
{
when(x){
Color.BLUE -> println("Battle")
else -> print("otherwise")
}
}
I get an error that says:
One type argument expected for class Enum<E: Enum<E>>
I've looked through Kotlin documentation for over an hour and I've got nothing to show for it... do any of you have an idea of how to use this class as a parameter?
enum creates a new class so you can use it as function argument type, as shown below.
For functions in kotlin see here.
fun getHexColor (x : Color)
{
when(x){
Color.BLUE -> println("Battle")
else -> print("otherwise")
}
}
You have to use the type which is Color:
fun getHexColor (x: Color) {
when(x){
Color.BLUE -> println("Battle")
else -> print("otherwise")
}
}
Note that a function prefixed with "get" should return something. Since when is an expression you can do it like this:
fun getHexColor (x: Color) = when(x) { // will return a String
Color.BLUE -> "Battle"
else -> "otherwise"
}
println(getHexColor(Color.BLUE))
Enum is actually special kind of class (it is even called enum class). So, use it as normal class and use benefits you get from it.
Example:
enum class X {
X, Y
}
fun check(param: X) {
val unit = when (param) {
X.X -> println("x")
X.Y -> println('y')
}
}
A function syntax in Kotlin looks like this:
fun double(x: Int): Int {
return 2 * x
}
where x is the name of the function parameter of type Int. Your function is not valid since you use Color as the parameter name rather than its type. To fix it do:
fun getHexColor (color: Color) {
when(color){
Color.BLUE -> println("Battle")
else -> print("otherwise")
}
}
You are able to do it like this with an interface for example:
enum class Color(val rgb: Int): IHexColor {
RED(0xFF0000){
override fun getHexColor() = rgb.toString()
},
GREEN(0x00FF00){
override fun getHexColor(): String = rgb.toString()
},
BLUE(0x0000FF){
override fun getHexColor(): String = rgb.toString()
}
}
interface IHexColor {
fun getHexColor(): String
}
#Test
fun testBasic() {
val red = Color.RED
val green = Color.GREEN
val blue = Color.BLUE
val palette = arrayListOf(red, green, blue)
palette.forEach {
println("Color: $it :: hex - ${it.getHexColor()}")
}
}
// output => Color: RED :: hex - 16711680, Color: GREEN :: hex - 65280, Color: BLUE :: hex - 255
How to use enum class:
fun useColorClass(color: Color){
println(color.rgb)
}
#Test
fun testColor() {
useColorClass(Color.RED)
useColorClass(Color.BLUE)
useColorClass(Color.GREEN)
}
// output => 16711680, 255, 65280
An answer for your question:
fun getHexColor (c: Color): String {
return when(x){
Color.BLUE -> println("Battle")
else -> print("otherwise")
}
}

`let` inside `let` in Kotlin: how to access the first `it`

I have one let inside another one
someMethodCall()?.let{
// ....
// some code here
// ....
val resultCall = it
someMethod2Call()?.let {
// ...
val myVariable = it + resultCall
// ...
}
}
Is it possible in Kotlin inside the second let get access to it of first let and avoid using resultCall variable?
it is a default name for the lambda argument. it is convenient for short lambdas, but you should not use it for longer lambdas. For longer lambdas make the code more readable by specifying an explicit argument name:
someMethodCall()?.let {
resultCall ->
// ... some code that uses "resultCall" instead of "it" ...
}
Use different names to avoid shadowing of the variable in the inner block as in your example:
someMethodCall()?.let {
resultCall ->
// ... some code here ...
someMethod2Call()?.let {
resultCall2 ->
// ...
val myVariable = resultCall2 + resultCall
// ...
}
No it's not possible and you should definitely use explicit names for the parameters in such use cases:
someMethodCall()?.let{ v1->
// ....
// some code here
// ....
someMethod2Call()?.let { v2->
}
}
It helps if you name your variables.
someMethodCall()?.let { resultCall ->
// ....
// some code here
// ....
someMethod2Call()?.let { otherResult ->
// ...
val myVariable = resultCall + otherResult
// ...
}
}
you can use this way
someMethodCall()?.let{ nameOne ->
// ....
// some code here
// ....
val resultCall = nameOne
someMethod2Call()?.let { -> nameTwo
// ...
val myVariable = nameTwo + resultCall
// ...
}
}

ANTLR4: no viable alternative at input (generate AST)

Well, I have a simple ANTLR code
whilestmt: 'while' exp 'do' stmt;
forstmt: 'for' VAR 'equal' exp TO exp 'do' stmt;
dosthstmt: 'something';
stmt: whilestmt|forstmt|dosthstmt;
exp: exp ADDOP exp #addterm
| fact #factterm
;
fact: INTLIT #intlit
| VAR #idlist
| LB exp RB #bracexp
;
WS : [ \t\r\n]+ -> skip ;
INTLIT : [0-9]+ ;
ADDOP: '+';
LB: '(';
RB: ')';
TO: 'to' | 'down to';
VAR: [a-z]+;
My Scala code:
import java.io.{PrintWriter,File}
import java.lang.RuntimeException
import org.antlr.v4.runtime.ANTLRFileStream
import org.antlr.v4.runtime.CommonTokenStream
object Main {
def main(args:Array[String]):Unit = {
val source = new ANTLRFileStream("test.txt")
val lexer = new ExpLexer(source)
val tokens = new CommonTokenStream(lexer)
val parser = new ExpParser(tokens)
val exp_parsetree = parser.exp()
//println(exptree.getClass)
val astgen = new ASTGeneration()
val exp_ast = exp_parsetree.accept(astgen)
println(exp_ast)
}
}
class ASTGeneration extends ExpBaseVisitor[ExpAST] {
override def visitWhilestmt(ctx: ExpParser.WhilestmtContext) = {
WhileAST(ctx.getChild(0).getText,ctx.exp.accept(this),ctx.getChild(1).getText,ctx.stmt.accept(this))
}
override def visitForstmt(ctx: ExpParser.ForstmtContext) = {
ForAST("for", ctx.VAR.accept(this), "equal", ctx.exp(1).accept(this), ctx.TO.accept(this) ,ctx.exp(1).accept(this), "do", ctx.stmt.accept(this))
}
override def visitDosthstmt(ctx: ExpParser.DosthstmtContext) = {
DosthAST("do something")
}
override def visitAddterm (ctx:ExpParser.AddtermContext) =
AddtermAST(ctx.exp(0).accept(this),ctx.getChild(1).getText,ctx.exp(1).accept(this))
override def visitFactterm(ctx:ExpParser.FacttermContext) =
ctx.fact.accept(this)
override def visitIntlit(ctx:ExpParser.IntlitContext) =
IntlitAST(ctx.INTLIT.getText.toInt)
override def visitIdlist(ctx:ExpParser.IdlistContext) =
IdAST(ctx.VAR.getText.toString)
override def visitBracexp(ctx:ExpParser.BracexpContext) =
ctx.exp.accept(this)
}
trait ExpAST
case class WhileAST(op:String,exp1:ExpAST, op2:String,exp2:ExpAST) extends ExpAST
case class ForAST(forr:String,varr:ExpAST, equal:String,exp1:ExpAST,to:ExpAST,exp2:ExpAST,doo:String,stmt:ExpAST) extends ExpAST
case class DosthAST(stmt:String) extends ExpAST
case class AddtermAST(left:ExpAST,op:String,right:ExpAST) extends ExpAST
case class IntlitAST(value:Int) extends ExpAST
case class IdAST(id:String) extends ExpAST`
I'm trying to generate a AST
My input: while 3 do something and the error:
line 1:0 no viable alternative at input 'while'
null
But the input 3+4, it works perfectly and the result is AddtermAST(IntlitAST(3),+,IntlitAST(4))
Can anyone help me with this ???
Thank you (Sorry for my bad English)
The entry point into your grammar is the exp rule.
val exp_parsetree = parser.exp()
Likely, you meant to use
val exp_parsetree = parser.stmt()
Of course, the input 3+4 is likely not to parse correctly -- it is just a bare exp.