Skip to content

Allow variable redefinition inside guarded self running blocks #2072

Closed

Description

@lukeapage
.a {
 @b: a;
 & when (@b = a) {
   @a: 10px;
 }
 b: @a;
}

In this case you get a syntax error from less. I propose it should work.

.a {
 @b: a;
 @a: 2px;
 & when (@b = a) {
   @a: 10px;
 }
 b: @a;
}

this case I am not sure about.

.a {
 @b: a;
 &.a when (@b = a) {
   @a: 5px;
 }
 b: @a;
}

this should stay as an error.

@seven-phases-max and @SomMeri what do you think?

I was trying to make code that redefined a couple of variables based on an option.

I guess the other way of doing it would be this

.a(@b) when (@b = true) {
   .a(12px);
}
.a(@b) when (@b = false) {
   .a(5px);
}
.a(@a) when (default() = true) {
 b: @a;
}

and maybe thats just clearer?

Activity

  1. seven-phases-max commented on Jun 25, 2014

    @seven-phases-max
    Member

    That's a difficult one to decide. Personally I get accustomed to think of & as of just ordinal CSS selector (which it actually is). So for me the current behaviour is less or more consistent:

    a {
        b {
            @c: 10px;
        }
        // no @c here
    }
    
    a {
        & {
            @c: 10px;
        }
        // no @c here as well
    }
    

    I can see the benefits of turning the & block into a sort of implicitly self-calling mixin, but I'm quite concerned of the implementation side. Notice that unlike mixins (which are expanded all at once at the point of their call), selectors (incl. &) are expanded at the point of their definition - so it may be quite problematic (if not impossible) to mimic all the (positive) side effects of a mixin expansion with &.
    In particular:


    [1].

    .mixin() {@a: 1}
    .mixin() {@a: 2}
    .mixin() {@a: 3}
    
    test {
        .mixin(); 
        a: @a; // -> 3
    }
    

    (typical use-case)
    Similar code with & won't work w/o special handling since later & expansions don't override variables of prev. expansions.


    [2].

    test {
       .mixin(); // guard is evaluated here (so default() knows of all the mixin definitions)
    
        // but:
        & when (default()) {@a: 1} // guard is evaluated right here but we have no idea of any other `&` definitions at this point :(
    
        // ...
    
        & {@a: 2}
    }
    

    W/o above features the & will hang somewhere in between mixins and ordinal selectors and create another "set of expansion rules" to remember (even if documented :).

  2. calvinjuarez commented on Jun 25, 2014

    @calvinjuarez
    Member

    So would & end up being something akin to JavaScript's this? 'Cause that seems rad.

  3. bassjobsen commented on Apr 8, 2015

    @bassjobsen
    Contributor

    i think (vote) that & when should have a special meaning; short for writing two mixins in once.

    The result of .mixin() { & when() {} } should be the same as .mixin() followed by .mixin when() where mixins evalute top bottom, having their own scope and leak variables as used with mixins as functions.

    In the current situation:

    .mixin(@a:0) {
        p: first;
        @v: 0;
    
        & when(@a = 1) {
        p: last;
        @v: 1;
        }
    }
    
    p {
        .mixin(1);
        v: @v;
    }
    

    compiles into:

    p {
      p: first;
      p: last;
      v: 0;
    }
    

    and:

    .mixin(@a:0) {
        p: first;
        @v: 0;        
    }
    .mixin(@a:0) when (@a = 1) {
        p: last;
        @v: 1;
    }
    
    p {
        .mixin(1);
        v: @v;
    }
    

    into:

    p {
      p: first;
      p: last;
      v: 1;
    }
    

    I think / expect both situation should have the same result:

    p {
      p: first;
      p: last;
      v: 1;
    }
    

    Also see: http://stackoverflow.com/questions/29496933/less-conditional-variable-change-inside-mixin/29497626

    ** some update **
    in fact the second mixing should possible read as:

    .mixin(@a:0) when (@a = 1) {
        p: first;
        @v: 0;    
        p: last;
        @v: 1;
    }
    

    But still expected @v = 1 due to last declaration wins

  4. calvinjuarez commented on Apr 8, 2015

    @calvinjuarez
    Member

    Very into .mixin() { & when(…) {…} }.

  5. SomMeri commented on Apr 8, 2015

    @SomMeri
    Member

    I prefer @seven-phases-max version, where & is considered just another selector. It seem more intuitive to me and also easier to explain/remember to users: this thing is just another example of selector, they behave the same way.

    Plus, I like that & allows us to sneak in 'private' variables that are sure not to overwrite caller scope.

  6. seven-phases-max commented on Apr 8, 2015

    @seven-phases-max
    Member

    Btw. my opinion about this feature shifted from somewhat neutral (as I expressed above) to "strictly no". This happened as I stepped into a few related Qs here and there at the SO and one issue ticket at the tracker. Now when I better see why exactly people tend to use it this way and how exactly they are going to use it... I can find more concerning pitfalls it will bring in (+ a few problems I missed earlier).

    So in summary:

    If it's going to be an if substitute we should not use & for it.

    ---

    In details.

    [1] Let's start with the following example:

    .a {
        result: @a;
        @a: 2px;
        & when (true) {
            @a: 10px;
        }
    }

    As you can see in above comments and in the linked SO question (actually there're a lot of exactly the same snippets at the SO) they clearly expect this to result in result: 10px. And a code like this will be the most often seen use-case for it. So for this change to actually work for those who vote it up, it has to override outer scope no matter what, basically breaking all scoping rules previously defined for rulesets and mixins. (So no, it's not going to be "just a shorthand for self-expanding mixin", as such mixin would result in 2px). Now accepting this as the base requirement, here're possible consequences and all sort of troubles it brings in:

    [2] Evading current scoping rules isn't a problem itself, but for sure it becomes a nice example of those "nonsensical and non-orthogonal/non-uniform scoping rules" they're talking about (falsely by now, but much harder to argue after this change). So when it will come to explaining/documenting this stuff it will be really hard to find any rationale for "why & when works this way but &.b when or even body when works that way" (yup, "just because" :).

    [3] (Probably the most important, strangely I missed this earlier) As noticed by @SomMeri above (and earlier in #1877) this also will break the pattern of using & {...} to isolate scopes. And while it probably never was "an official" usage thing, this pattern is a natural corollary of the normal ruleset scoping rules. So, considering backward compatibility and the fact that this pattern went relatively wide-spread (at least I estimate so) by now, this change most likely will instantly break a lot of code out there. (Even not counting backward compatibility, we'll then have to invent another straight-forward and "clean" method to use to put those various "scope-leaking side-effects" under predictable control when nothing else can help).

    [4] Blurring & semantics. By now, & does not really have any special scoping rules, except that, indeed, since v1.6.2 the CSS properties it generates are expanded directly into the outer scope. But this was made only for the sake of the output CSS optimization (simply to eliminate redundant duplicated selectors) and wasn't really meant to alter any Less code itself (obviously CSS is flat and does not have any scope, but Less has). So & {...} still can be considered as an ordinal ruleset (after all this is why it is allowed to use & when syntax at all: only because it is a ruleset too) and & is still just what "Parent Selectors" says it to be (technically just "an alias for a selector of the current ruleset"). This change will turn & into "a (magical) Less ruleset scope cracker", thus loading it with a brand new semantics that has almost nothing to do with its original meaning ("selector shorthand keyword" vs. "ruleset auto-expansion directive"), thus making the whole "Parent Selectors" + "Scope Cracker" combo more ambiguous to define and understand. In other words, next time you see & in code it will require much more attention to find if it's used as a "parent selector" or as a "scope cracker" (or both, with the latter being yet more unpredictable/unclear in "how-to-use" since (as of [2]) it no longer follows normal scope rules, which brings us to [5]).

    [5] We all know that the lazy-loading stuff (and the "declarativeness" of Less in general) is probably the last thing most new users (at least those with PHP/JavaScript/"name-your-scripting-language" background) become aware of. So we'll have to be prepared for all sorts of weird code like:

    div {
        @a: 5;
        a {
            & when (@a > 5) {
                @a: 2;
            }
            & when (@a < 3) {
                @a: 10;
            }
            & when (@a > 6) and not(something-else) {
                @a: boo!;
            }
    
            result: @a;
        }
    }

    to jump in, all marked as Less bugs. "WTF is this lazy-loading ur talking about? I have exactly the same code working perfect in PHP!" :). Really, just take any arbitrary if snippet out there, replace if with & when (that's what they usually do) and see what happens with lazy-loading. So this also becomes a maintenance/support nightmare as it encourages brainless copy-pastes from "name-your-favorite-language" (for now they at least have to notion Less basic principles earlier when doing their search for "conditional code in Less" or so). This of course is no way an issue of this feature or a reason to not enable it, but if there's some (other syntax?) way we could target this earlier (or at least minimize possible recursive dependencies vs. lazy-loading conflicts) we're better to try to search for such way before making the changes.

    ---

    So for the ending summary:

    While I still sympathize this (quite big new as it turns out to be actually) feature in general, I believe it should be <something-else> when instead of & when (and & when itself to stay as-is, assuming fixed #1877 then).
    Even if that would require a new keyword/directive it will be definitely worth by cutting [3], [4] and partially [2] things off.
    [5] remains, but it's another big story to think of so I have no real ideas currently (earlier this was mentioned regarding mixin guards that can also suffer from such recursion in certain cases and the possibility to detect such stuff (to throw a error when unsolvable) was estimated as too complicated).

    Speaking of <something-else>, also no good ideas yet but in sketching mode:

    • just when? (suffering from typos though)
    • finally, if it's if why not if (or some derivative)? no hypocrisy! :) (this will make [5] much more dramatic though).
  7. bassjobsen commented on Apr 8, 2015

    @bassjobsen
    Contributor

    @seven-phases-max thanks for your extended answer in the first place. I do really appreciate that. I will have to think about all this. For now it seems you says everything about a & should act the same, and i possible argue that & when and & .selector are different cause the first is a guard and the second a selector.

    A new ... for & when possible solve that indeed. A new & when possible introduce new issues. Till now i did not found any issues with the current & when except when using it for mixins as functions.

    update
    okay i understand now when & when becomes a self-expanding mixin then also & {} should become such a mixin. The latest will break many other things.

  8. SomMeri commented on Apr 9, 2015

    @SomMeri
    Member

    In general I would be favorable to syntactic sugar around often used cases that are currently either long or hard to read. Things that are just syntactic sugar tend to be easy to implement if the syntax is designed right, so why not if they add real value to the user.

    The rules less respects so far and we might not want to break without good reason:

    • {} creates new scope everywhere else,
    • less is declarative language not procedural one.

    When user need to declare single variable, a simple if or when function or ? : operator could already help:

    //ternary operator is standard
    @variable: when(condition, ifTrue, ifFalse);
    @variable: if(condition, ifTrue, ifFalse);
    @variable: ?(condition, ifTrue, ifFalse); 

    When multiple variables depend on the same condition, we could use new symbol for non-scope creating blocks. For example [block]:

    if (condition) [ 
      // variables defined here override local scope
    ] elif (condition) [
    ] else [
    ]

    It could be just a syntactic sugar for conditional mixins + slight different handling of return values.

  9. matthew-dean commented on Apr 10, 2015

    @matthew-dean
    Member

    XSLT is a good reference for a declarative language that is still very functionally expressive. I'm not a fan of introducing big logic blocks. BUUUT single line evaluations would seem to fit, because we already use them in part for things like the contrast function:

    value: contrast(#222222, #101010, #dddddd, 30%);
    

    This is basically the same as this pseudocode:

    value: if(lightness(#222222) > 30%, #101010, #dddddd);
    

    They both evaluate against a value, and return a result depending on the test. And, in truth, the second is probably easier to logically follow than the contrast function itself (it's self-documenting), and allows more expressiveness.

    So, to go back to @lukeapage's example:

    .a {
     @b: a;
     @a: 2px;
     & when (@b = a) {
       @a: 10px;
     }
     b: @a;
    }
    

    This becomes:

    .a {
     @b: a;
     @a: if(@b = a, 10px, 2px);
     b: @a;
    }
    

    It's a hell of a lot easier to read, and we don't have to dick around with & when and block scoping stuff. We already use "if-like" functions, so why not just an if function?

  10. matthew-dean commented on Apr 10, 2015

    @matthew-dean
    Member

    Side note: spreadsheet functions are also a good example for declarative programming functions.

  11. matthew-dean commented on Apr 10, 2015

    @matthew-dean
    Member

    Oh, and second side note: I just realized in the contrast example that I'm not sure if it's less than 30% or greater than 30% that results in the first value being returned, which emphasizes my point. I would use an if function to test for light / dark rather than contrast, because while it's more verbose, it would be more maintainable.

  12. seven-phases-max commented on Apr 10, 2015

    @seven-phases-max
    Member

    @a: if(@b = a, 10px, 2px);

    Which is basically #1894.

    Btw., XSLT has if statement and it works exactly like Less * when() {} now - it can't redefine values and variables in outer blocks....

    P.S. Curously xsl:when is (sort of) the function that we would need for stuff like @a: if(@b = a, 10px, 2px); to be possible (currently you can't use logical operators in Less anywhere except after its when), i.e. in the end this whole stuff would look something like that: @a: select(when(x = y), 10px, 2px); (such function would need select or choose (hello XSLT again :) name instead of if for obvious reasons (and when to be a special pseudo-function like url).

  13. 27 remaining items

  14. matthew-dean commented on Apr 13, 2015

    @matthew-dean
    Member

    The examples you give are imperative patterns, which tell the compiler a precise control flow. If we are extending when from mixin syntax, it doesn't make sense to have a different control flow than used with mixins, or to suddenly include an imperative flow in a declarative language. To follow Less's model, you'd want to think of when and else (or default()) as guards you are "binding" to something, which will then be evaluated as a group by the compiler. The reason why mixin guards work without a @select group is because all of those statements are bound to the same mixin name, so the "default" applies to that mixin group.

    Similarly, all the examples of possible failures would apply to anywhere else where we currently use when guards, which no one has really complained about. In other words, I think you're describing a complicated issue which could exist, but there's no reason to think it does it already. And if in an edge case, someone wants to nest when statements, there's nothing more complicated to that than having a mixin call inside another mixin call, where both have guards. So, if these problematic patterns were to exist, they already exist, and this syntax wouldn't be introducing those problems. I don't think it's worth changing the nature of the Less language and declarative blocks in order to solve patterns people haven't asked about yet.

    In essence, what I'm describing is something like "anonymous guards". They're not bound to any selector block or mixin definition. They evaluate and return to their current scoped block. This would be a familiar addition to Less authors that are already using guards on mixins, which also has an advantage over the "functional" syntax discussed earlier. The pattern is already used extensively in Less. (However, it's possible that we could still also introduce a simple binary if/then/else function for simpler conditions and use cases. The problem would be how to write those conditions.)

  15. matthew-dean commented on Apr 13, 2015

    @matthew-dean
    Member

    Also, another consideration could be a guard condition on the select statement.

    @select when (cond) {
      @when (cond) {
      }
      @when (default()) {
      } 
    }
    
  16. SomMeri commented on Apr 23, 2015

    @SomMeri
    Member

    @matthew-dean Mixins are named, so you can have one default() for one mixin and entirely different default() for another mixin. E.g. the border() mixin is not forced to share default implementation with transformation() mixin.

    The examples are cases where you might want multiple different when within the same block, but can not because they share the same else clause by language design. Basically, if we do not add else to when, then we are limiting what is possible to do with the language - you can have only one full conditional statement within the same block.

    I do see how it changes the nature of less language itself. It just changes how the feature is implemented. We can not straightforwardly convert all when statements within the same block into nameless mixin - we would had to give everyone different name. But that is just relatively small implementation issue, not a language one.

  17. seven-phases-max commented on Aug 7, 2015

    @seven-phases-max
    Member

    A bit of offtopic, but somewhat related. I've just occasionally remembered an old trick that I think would be fun to share here (from "Branch-free based programming in Less", Chapter 6: "Table-Lookups").
    Gist (and Codepen demo for the same thing). It's actually two tricks in one: there the @alt-color is actually a function (trick one) that uses a table-lookup (trick two) to emulate contrast function w/o any conditional stuff or guards or whatever.

  18. added this to the 3.0 milestone on Apr 29, 2016
  19. seven-phases-max commented on Apr 30, 2016

    @seven-phases-max
    Member

    Btw. (inspired by recent topics referenced above), since I'm not a great fan of the idea of bringing in @custom directive syntax for Less specific features, I would like to also mention an alternative syntax:

        :when (...)

    (with or without optional &).

  20. matthew-dean commented on Apr 30, 2016

    @matthew-dean
    Member

    The only thing to remember is that & when is not evaluated like @when, and both of those have more predictable allegories; e.g. selector guards and media queries, respectively. :when would not have a predictable behavior (which does not make it worse, but something of note).

    That said, even having proposed @when, I too am reluctant about adding @-rules to Less. It's a) kind of Sass-y, and b) muddies var definition syntax, c) muddies existing CSS @-rules, d) potentially conflicts with the existing PR / 3.0 discussion about allowing plugins to define custom @-rules. (Under debate: #2852 & less/less-meta#10)

    So, ':when' is an interesting suggestion. I would suggest that as to this:

    (with or without optional &).

    If we did that, then the same optionality should exist for &:extend, as those would then be somewhat congruous as far as syntax.

  21. matthew-dean commented on May 4, 2016

    @matthew-dean
    Member

    Some other possibilities:

    1. when as a Less "flag" (e.g. `!important)

    .something (@a, @b) {
      @x: 1;
      !when (@a=1) {
        @x: 2;
      }
    }
    

    or

    2. GUARD ALL THE THINGZ

    These are all separate ideas.

    // guard on a value
    .something (@a, @b) {
      @x: 1;
      @x: 2 when (@a=1);
      // or would possibly need the flag at this point
      @x: 2 !when (@a=1);
    }
    //or guard on an anonymous ruleset
    .something-else (@a, @b) {
      @x: 1;
      { @x: 2; } when (@a=1);   // scoping gets confusing here, and confused with `& when` so probably not
    }
    // or guard on a detached ruleset
    .something-else-else (@a, @b) {
      @x: 1;
      @dr: { @x: 2; };
      @dr() when (@a=1);   // requires proposed change to DR var scope
    }
    // or guard on an evaluated lambda
    .something-else-else-else (@a, @b) {
      @x: 1;
      @() { @x: 2 } when (@a=1);   // self-executing lambda (anonymous mixin)?
      // or written possibly as
      @() when (@a=1) { @x: 2 };
    }
    // or
    .something-else-else-else-else (@a, @b) {
      @x: 1;
      @dr: () when (@a=1) { @x: 2 };  // pie-in-the-sky: var assigned to lambda with guard (DR w/ mixin features)
      @dr();  
    }

    The latter sketches are me just thinking about if we could basically cover "when" cases with two existing Less.js proposals: 1) lambdas and 2) DR/mixin unification.

  22. calvinjuarez commented on Jun 24, 2016

    @calvinjuarez
    Member

    I'd love to be able to do something like this:

    (when (@a = 1): { @x: 2; })();
    // OR
    @(when (@a = 1): { @x: 2; })();
    // optionally without the `:`s

    I'm borrowing the JS anon self-calling function syntax, which seems most familiar and explicit to me.

    ALSO,

    Do the () in a detached ruleset call do anything at the moment, or is it just mixin-like syntax? Is there a plan for those?

  23. stale commented on Nov 14, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions