You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Unify Mixin and DR behaviour (and related Functions stuff) #16
As dissucussed in #2767, current DR and Mixin call result (visibility of their internal entities in the caller scope) is somewhat inconsistent. In particular, mixin calls exposes both internal mixins and variables, but DR calls keep its variables hidden:
The proposal is to match both (per #2767 by exposing DR variables too).
The exposed variables ("callee variables") have the lowest priority (i.e. never override caller's local or parent scope variables), thus the change will not break any existing Less code.
Edit: My mistake above: callee variables do override caller's parent (incl. global) variables, thus the change is breaking for snippets like:
@my-red-theme: {
@color: red;
};
@color: blue;
.btn {
@my-red-theme();
color: @color; // blue -> red
}
Is there any logic to going the other way in 3.0? Just in terms of simplifying the compiler, it seems like Less sometimes has to do a number of evaluation passes to settle all the variables exposed to different scopes. If you had to design variable scope from scratch in Less, would you do it this way?
Also, I think this was discussed elsewhere, but it might be a good opportunity to change the definition of "Detached Ruleset" to "Anonymous Mixin", with a change like:
// silly example but here ya go@my-red-theme: (@newcolor) {
@color: @newcolor;
};
.btn {
@my-red-theme(red);
border-color: @color; // red
}
I just mean if we were to allow someone to pass in parameters as a mixin (and we're aligning variable behavior with mixins), then it would be an anonymous mixin.
Variables and mixins defined in a mixin are visible and can be used in caller's scope. There is only one exception, a variable is not copied if the caller contains a variable with the same name (that includes variables defined by another mixin call). Only variables present in callers local scope are protected. Variables inherited from parent scopes are overridden.
What is the rationale for this? I didn't realize that a mixin had exceptions where it didn't copy a variable. Isn't it inconsistent that it mixins variables some times and not others? And, as noted by the documentation, it doesn't protect variables from the parent scope.
Also, because of this behavior, you get add-on weirdness like this:
In my mind, this would be simpler to define that mixins either add variables to the scope, or they don't. This exception just makes for a confusing mess of behaviors.
Can you think of a reason why this behavior is justified?
...I'm wondering if we should not match mixin behavior to DRs, rather than the other way around. That is, isolate variables within the scope of mixins, if you can solve return variables with a declarative syntax. If you can explicitly pass in variables to a mixin, and explicitly return variables, it seems like that would greatly simplify evaluation if the internal variables were isolated, because the mixin would always return the same results, given the same values, regardless of scope.
That is, this would throw an errorthis would maybe throw an error. There are a collection of scoping rules, and I noticed that DRs, when called, can still see the caller's scope. So maybe mixins/DRs would retain that behavior and not throw an error with the following:
.mixin(): @a {
@a: foo;
}
.test {
bar: .mixin(); // we're all good
}
Breaking behavior is not always great. But.... mixin scope and the explanation of caller/callee scope is not a simple concept in Less. My guess is that caller scope is not a relied-upon behavior (maybe), and likely more often than not creates unexpected side-effects. And we're already on the page of recognizing that having different scoping rules for DRs and mixins is not ideal. So maybe let's go the other way, since isolating variable scope is way easier to reason about.
_EDIT: As noted above, we could isolate variables/mixins from returning to the caller scope, but it's possible we can/should retain visibility of caller scope from within the mixin call. I didn't realize when I first wrote this up that that's current DR behavior._
This would also eliminate counter-intuitive patched-on rules like "Variables defined directly in callers scope cannot be overridden. However, variables defined in callers parent scope is not protected and will be overridden." Basically, variables in caller's scope would always be safe.
Also, considering what I've seen in the ruleset evaluation step of Less.js, I think this could give a performance boost, because it would reduce the amount of splicing / array flattening that currently happens, as well as variable lookup time (because of fewer variables and fewer loop iterations), whereas increasing variable visibility for DRs would theoretically reduce performance. Also, one advantage of @rjgotten's syntax as opposed to other proposals is that the mixin doesn't have to be evaluated to determine that a value other than a ruleset will be produced. The mixin can be flagged statically when it's defined.
the mixin doesn't have to be evaluated to determine that a value other than a ruleset will be produced. The mixin can be flagged statically when it's defined.
I.e. Mixin-as-mixin calls could early-out on all signatures that were flagged by the parser as having an out-parameter. And vice-versa; mixin-as-function calls could early-out on all signatures that were flagged as not having an out-parameter. Both at (virtually) no additional cost.
This and the fact that it plays nicely with Less's declarative nature are exactly the two primary reasons I proposed this particular syntax.
This happened to come to me while I was working this week on finishing up 3.0 for release. (It's now in alpha if you can please check it out.)
It occurred to me: Instead of being able to call mixins from anywhere and use them as functions (i.e. an "out" value), I think we've already effectively solved this with the discussion in #12 (e.g. #12 (comment))
That is: rather than the "variable return assignment syntax", this is my proposal.
We consider the return value of both Mixins and Detached Rulesets as a "Less List" of rules, which of course will be mixed into the parent ruleset when called, by default.
We can access members of that list (and return their values) by key, which will either be a variable or property, using [].
In addition, I was thinking we could treat Less lists similar to PHP arrays, which can be indexed by number or key (or both), and use [] as shorthand for the extract() function. So that you can write the above example as:
(Numerical access is not necessary, just an idea to normalize across lists, such that you could possibly also do extract(@list, 'key') or use @list[3] vs. extract(@list, 3). This could be a later-stage proposal.)
Since Less lists are not mutable, we don't need to add any other kind of array-like manipulation capability. And of course, this allows a great deal of flexibility with name-spacing and variables.
/* ui-library.less */#lib() {
.colors() {
primary: blue;
}
}
/* custom.less */@include"ui-library";
// Override library vars// Note: You can't name-space a mixin like this but it would be convenient#lib.colors() {
primary: red;
}
.button {
background: #lib.colors['primary']; // background: red;
}
Note, keys are quoted to make it clear that the key is not a local variable, which is still a possibility.
The above pattern could be very powerful, as you could effectively have the same mixin apply & consume different namespaced values. (In other words, the .button class above could be rewritten as a re-usable mixin.)
So that's the main pieces of this proposal. And, just to re-state, we could continue forward with the breaking change of not leaking variables from mixins into the parent, and have variables private like detached rulesets do now. That would greatly simplify the two (and the documentation).
One issue I see with this, is that outside consumers calling a mixin will need to have knowledge of the internal details of the mixin (i.e. the variable name they need to extract). That limits re-use, especially if said mixin comes from an @import 4 layers down in the guts of a framework or library.
@rjgotten True, but how is that different than exposing variables into the parent scope? If you're going to use those values, then yes, you need to know the name of the variable / property returned by the mixin. The knowledge needed by the developer does not change. You could also argue that this makes the code more self-documenting. That is: right now, if you use a variable returned by a mixin, it's not clear at all from the point of the mixin call if that variable is from the mixin or just happens to be a variable available from further up the scope chain.
For example:
/* Less 0.x-3.x */// @import... @import... etc..element {
.mixin;
value: @arbitraryvar; // from.... where exactly?
}
vs.
/* Less 4.x+ */// @import... @import... etc..element {
value: .mixin['@arbitraryvar']; // ah, it's available in this mixin
}
// Less 4.x#usage {
.my-theme-ns(red).some-mixin();
border: 1pxsolid.my-theme-ns(red)[@secondary];
}
Though I'm not sure how easy it would be to modify the parser to support an arbitrary count of subsequent subscript/call operators... i.e.: foo(...)(...).bar(...)[...](...)[...][...].baz[...](...) // <- valid code. So it's could be spread over Less 3.x-5.x.
changed the title [-]Matching Mixin and DR behaviour (and related Functions stuff)[/-][+]Unify Mixin and DR behaviour (and related Functions stuff)[/+]on May 31, 2018
After writing up this example, I was wondering if maybe @seven-phases-max's original proposal wasn't the correct one. That is, aligning behavior by exposing vars from VariableCalls (like MixinCalls) vs the opposite (making MixinCall vars private).
Further to that, I'm wondering if we can't "fix" variables dumped into callee scope by changing precedence, such that the inherited declared vars take precedence over mixincall merged ones.
In other words, the variables declared in selectors take precedence. So, mixin call vars are still merged into callee rules, but marked as merged, and during variable lookup, the cascade gives un-merged vars a higher weight.
I feel like this is less of a breaking change, for both mixin calls, and then if we align to variable calls. Consider the following:
I feel like we'd get waaaay fewer complaints about this than causing MixinCalls to error where it currently does not. Instead we cause VariableCalls to NOT error, but also NOT override inherited vars, which would effectively preserve behavior and not be a breaking change for it.
We also would no longer have to "switch" behavior of MixinCalls based on whether or not it finds a variable in the immediate callee scope. Instead, it just faithfully merges all its vars, but it's during evaluation where we find out if it's needed or not. It just has lower precedence.
What do you think? I feel like this is the "safer" breaking change and still aligns the two types.
It's safer from a code-migration point of view, but one of the driving points of making mixin variables private is to mirror behavior of nearly every programming language out there; none of which leak local variables outward without some explicit return mechanism. It's basic principle of least astonishment, in that sense.
Using leaking variables as a return mechanism also means mixin consumers need to know about the internals of a mixin, i.e. they need to know what variable names to access.
I also feel like there is quite a bit of complexity and ambiguity in the Less parser due to this mechanism. It requires some rather weird kludges with detecting not-yet-existing variables and postpone bits of logic that need them to run; trying to execute all possible mixins within the current ruleset scope to get them to appear; then resuming with the remainder of the logic in the ruleset scope. Add the possibility of this pattern occuring in nested sequences; or how it interplays with order-dependency of some other parts of the language; ... ouch.
If you make mixin variables private and use an explicit return mechanic, it becomes much easier to statically analyze the code into a dependency call-tree and evaluate everything in order in a robust, predictable way.
If you make mixin variables private and use an explicit return mechanic, it becomes much easier to statically analyze the code into a dependency call-tree and evaluate everything in order in a robust, predictable way.
Okay, fair enough. I don't disagree with the principle at all. I'm just being pragmatic. I'm also not sure if we mentioned it, but I think this is possibly even more problematic:
#ns {
.mixin();
}
.foo {
#ns();
.mixin(); // this is weird
}
You can already do #ns.mixin();, so I'm not even sure why this exists, and it seems like it would lead to not the least astonishment, as you put it.
Okay, I hear you, and I'm fine to keep moving forward to privatizing mixin members in 4.0 or whatever the next breaking change release would be.
I think the suggestion to mark variables as 'exported' and to alter their precedence, is a good transitionary solution. It will help clean up some mess now, and can lead up to a breaking change in a later major version.
I think the suggestion to mark variables as 'exported' and to alter their precedence, is a good transitionary solution.
Good to know. It certainly would help simplify the docs in the short term. To be clear, though, this (setting lower precedence to merged vars) would also be a breaking change. But minor.
(I think we'll never should allow any DR/mixin/ruleset calls w/o () anymore). - @seven-phases-max
This has been my conclusion too since writing up tests and implementing namespacing. .mixin; should not be deprecated as a mixin call. Fine to mark that in the docs as deprecated?
2. Exports
Rather than re-visiting named exports, what if we just did something simple like returning the last rule's value if the lookup value is empty? As in:
.add(@p, @x) {
@r: @p+@x;
}
.foo {
width: .add(10px, 10px)[]; // returns last rule @r's value
}
It's a very simple change in terms of parsing and lookup. Or @seven-phases-max@rjgotten et. all do you think some special character should indicate the last value? Like .add(10px, 10px)[/]?
With something like that, we could serve not having to write the arbitrary return lookup variable name when using lookups for function-like mixins.
3. Other?
Anything else outstanding from this thread not implemented or resolved?
Cool. Do you want to check out the PR and see if the usage makes sense?
One thing I wasn’t sure of: [] takes the final declaration value, regardless of whether it’s a variable or prop value. I wasn’t sure if it should be just variable declarations. But this seemed the most straightforward.
Activity
matthew-dean commentedon May 3, 2016
👍
matthew-dean commentedon Jul 2, 2016
Is there any logic to going the other way in 3.0? Just in terms of simplifying the compiler, it seems like Less sometimes has to do a number of evaluation passes to settle all the variables exposed to different scopes. If you had to design variable scope from scratch in Less, would you do it this way?
matthew-dean commentedon Jul 2, 2016
Also, I think this was discussed elsewhere, but it might be a good opportunity to change the definition of "Detached Ruleset" to "Anonymous Mixin", with a change like:
seven-phases-max commentedon Jul 3, 2016
"Anonymous Ruleset" probably, "mixin" would be somewhat...
matthew-dean commentedon Jul 3, 2016
I just mean if we were to allow someone to pass in parameters as a mixin (and we're aligning variable behavior with mixins), then it would be an anonymous mixin.
matthew-dean commentedon Jul 14, 2016
One thing about variables: from this section, http://lesscss.org/features/#mixins-as-functions-feature, this part is baffling to me:
What is the rationale for this? I didn't realize that a mixin had exceptions where it didn't copy a variable. Isn't it inconsistent that it mixins variables some times and not others? And, as noted by the documentation, it doesn't protect variables from the parent scope.
Also, because of this behavior, you get add-on weirdness like this:
In my mind, this would be simpler to define that mixins either add variables to the scope, or they don't. This exception just makes for a confusing mess of behaviors.
Can you think of a reason why this behavior is justified?
matthew-dean commentedon Sep 27, 2016
Per @rjgotten's comment here: less/less.js#538 (comment)
...I'm wondering if we should not match mixin behavior to DRs, rather than the other way around. That is, isolate variables within the scope of mixins, if you can solve return variables with a declarative syntax. If you can explicitly pass in variables to a mixin, and explicitly return variables, it seems like that would greatly simplify evaluation if the internal variables were isolated, because the mixin would always return the same results, given the same values, regardless of scope.
That is,
this would throw an errorthis would maybe throw an error. There are a collection of scoping rules, and I noticed that DRs, when called, can still see the caller's scope. So maybe mixins/DRs would retain that behavior and not throw an error with the following:This would not throw an error (variable definitions in scope of mixin definition):
Like detached rulesets, this would throw an error:
BUT with @rjgotten's syntax, you could do:
Breaking behavior is not always great. But.... mixin scope and the explanation of caller/callee scope is not a simple concept in Less. My guess is that caller scope is not a relied-upon behavior (maybe), and likely more often than not creates unexpected side-effects. And we're already on the page of recognizing that having different scoping rules for DRs and mixins is not ideal. So maybe let's go the other way, since isolating variable scope is way easier to reason about.
_EDIT: As noted above, we could isolate variables/mixins from returning to the caller scope, but it's possible we can/should retain visibility of caller scope from within the mixin call. I didn't realize when I first wrote this up that that's current DR behavior._
This would also eliminate counter-intuitive patched-on rules like "Variables defined directly in callers scope cannot be overridden. However, variables defined in callers parent scope is not protected and will be overridden." Basically, variables in caller's scope would always be safe.
matthew-dean commentedon Sep 27, 2016
Just to see how this would affect the documentation, I found that most of the "Mixins as functions" documentation could be eliminated with this change. See: https://github.com/less/less-meta/blob/master/proposal/mixins-as-functions.md
Also, considering what I've seen in the ruleset evaluation step of Less.js, I think this could give a performance boost, because it would reduce the amount of splicing / array flattening that currently happens, as well as variable lookup time (because of fewer variables and fewer loop iterations), whereas increasing variable visibility for DRs would theoretically reduce performance. Also, one advantage of @rjgotten's syntax as opposed to other proposals is that the mixin doesn't have to be evaluated to determine that a value other than a ruleset will be produced. The mixin can be flagged statically when it's defined.
rjgotten commentedon Nov 8, 2016
I.e. Mixin-as-mixin calls could early-out on all signatures that were flagged by the parser as having an out-parameter. And vice-versa; mixin-as-function calls could early-out on all signatures that were flagged as not having an out-parameter. Both at (virtually) no additional cost.
This and the fact that it plays nicely with Less's declarative nature are exactly the two primary reasons I proposed this particular syntax.
matthew-dean commentedon Jan 2, 2017
I have an alternate suggestion for this thread.
This happened to come to me while I was working this week on finishing up 3.0 for release. (It's now in alpha if you can please check it out.)
It occurred to me: Instead of being able to call mixins from anywhere and use them as functions (i.e. an "out" value), I think we've already effectively solved this with the discussion in #12 (e.g. #12 (comment))
That is: rather than the "variable return assignment syntax", this is my proposal.
[].We can effectively get arbitrary "out values" like this:
In addition, I was thinking we could treat Less lists similar to PHP arrays, which can be indexed by number or key (or both), and use
[]as shorthand for theextract()function. So that you can write the above example as:(Numerical access is not necessary, just an idea to normalize across lists, such that you could possibly also do
extract(@list, 'key')or use@list[3]vs.extract(@list, 3). This could be a later-stage proposal.)Since Less lists are not mutable, we don't need to add any other kind of array-like manipulation capability. And of course, this allows a great deal of flexibility with name-spacing and variables.
Note, keys are quoted to make it clear that the key is not a local variable, which is still a possibility.
The above pattern could be very powerful, as you could effectively have the same mixin apply & consume different namespaced values. (In other words, the
.buttonclass above could be rewritten as a re-usable mixin.)So that's the main pieces of this proposal. And, just to re-state, we could continue forward with the breaking change of not leaking variables from mixins into the parent, and have variables private like detached rulesets do now. That would greatly simplify the two (and the documentation).
Thoughts welcome.
rjgotten commentedon Jan 2, 2017
One issue I see with this, is that outside consumers calling a mixin will need to have knowledge of the internal details of the mixin (i.e. the variable name they need to extract). That limits re-use, especially if said mixin comes from an
@import4 layers down in the guts of a framework or library.matthew-dean commentedon Jan 2, 2017
@rjgotten True, but how is that different than exposing variables into the parent scope? If you're going to use those values, then yes, you need to know the name of the variable / property returned by the mixin. The knowledge needed by the developer does not change. You could also argue that this makes the code more self-documenting. That is: right now, if you use a variable returned by a mixin, it's not clear at all from the point of the mixin call if that variable is from the mixin or just happens to be a variable available from further up the scope chain.
For example:
vs.
55 remaining items
matthew-dean commentedon Jun 6, 2017
@rjgotten Yeah this is in a pretty good place now. I think there is enough consensus in this thread to make it a 4.0 recommended feature?
seven-phases-max commentedon Jun 7, 2017
Yes.
Though I'm not sure how easy it would be to modify the parser to support an arbitrary count of subsequent subscript/call operators... i.e.:
foo(...)(...).bar(...)[...](...)[...][...].baz[...](...) // <- valid code. So it's could be spread overLess 3.x-5.x.matthew-dean commentedon Oct 9, 2017
Can someone write up a summary of the recommended feature that we reached consensus on and post a proper feature request to less/less.js?
matthew-dean commentedon Feb 6, 2018
@less/core Hold off on writing up a proposal until #12 is finalized.
[-]Matching Mixin and DR behaviour (and related Functions stuff)[/-][+]Unify Mixin and DR behaviour (and related Functions stuff)[/+]matthew-dean commentedon Jun 29, 2018
So have a look at this comment on this PR: less/less.js#3242 (comment)
After writing up this example, I was wondering if maybe @seven-phases-max's original proposal wasn't the correct one. That is, aligning behavior by exposing vars from VariableCalls (like MixinCalls) vs the opposite (making MixinCall vars private).
Further to that, I'm wondering if we can't "fix" variables dumped into callee scope by changing precedence, such that the inherited declared vars take precedence over mixincall merged ones.
For example, currently this is the case:
Input (current):
Output (current):
So far in this thread, we've been leaning this way if we change mixins to have private vars:
I propose that we make the result this:
Output (proposed):
In other words, the variables declared in selectors take precedence. So, mixin call vars are still merged into callee rules, but marked as merged, and during variable lookup, the cascade gives un-merged vars a higher weight.
I feel like this is less of a breaking change, for both mixin calls, and then if we align to variable calls. Consider the following:
Input (current):
Output (current):
With my proposed change, we would still keep the output the same, except no error in this case:
Output (proposed):
I feel like we'd get waaaay fewer complaints about this than causing MixinCalls to error where it currently does not. Instead we cause VariableCalls to NOT error, but also NOT override inherited vars, which would effectively preserve behavior and not be a breaking change for it.
We also would no longer have to "switch" behavior of MixinCalls based on whether or not it finds a variable in the immediate callee scope. Instead, it just faithfully merges all its vars, but it's during evaluation where we find out if it's needed or not. It just has lower precedence.
What do you think? I feel like this is the "safer" breaking change and still aligns the two types.
rjgotten commentedon Jul 1, 2018
It's safer from a code-migration point of view, but one of the driving points of making mixin variables private is to mirror behavior of nearly every programming language out there; none of which leak local variables outward without some explicit return mechanism. It's basic principle of least astonishment, in that sense.
Using leaking variables as a return mechanism also means mixin consumers need to know about the internals of a mixin, i.e. they need to know what variable names to access.
I also feel like there is quite a bit of complexity and ambiguity in the Less parser due to this mechanism. It requires some rather weird kludges with detecting not-yet-existing variables and postpone bits of logic that need them to run; trying to execute all possible mixins within the current ruleset scope to get them to appear; then resuming with the remainder of the logic in the ruleset scope. Add the possibility of this pattern occuring in nested sequences; or how it interplays with order-dependency of some other parts of the language; ... ouch.
If you make mixin variables private and use an explicit return mechanic, it becomes much easier to statically analyze the code into a dependency call-tree and evaluate everything in order in a robust, predictable way.
matthew-dean commentedon Jul 1, 2018
Okay, fair enough. I don't disagree with the principle at all. I'm just being pragmatic. I'm also not sure if we mentioned it, but I think this is possibly even more problematic:
You can already do
#ns.mixin();, so I'm not even sure why this exists, and it seems like it would lead to not the least astonishment, as you put it.Okay, I hear you, and I'm fine to keep moving forward to privatizing mixin members in 4.0 or whatever the next breaking change release would be.
rjgotten commentedon Jul 2, 2018
Don't get me wrong though.
I think the suggestion to mark variables as 'exported' and to alter their precedence, is a good transitionary solution. It will help clean up some mess now, and can lead up to a breaking change in a later major version.
As you wrote: it's pragmatic.
matthew-dean commentedon Jul 2, 2018
Good to know. It certainly would help simplify the docs in the short term. To be clear, though, this (setting lower precedence to merged vars) would also be a breaking change. But minor.
matthew-dean commentedon Jul 3, 2018
Just some clean-up to do on this feature.
1. Deprecating mixin calls without
()This has been my conclusion too since writing up tests and implementing namespacing.
.mixin;should not be deprecated as a mixin call. Fine to mark that in the docs as deprecated?2. Exports
Rather than re-visiting named exports, what if we just did something simple like returning the last rule's value if the lookup value is empty? As in:
It's a very simple change in terms of parsing and lookup. Or @seven-phases-max @rjgotten et. all do you think some special character should indicate the last value? Like
.add(10px, 10px)[/]?With something like that, we could serve not having to write the arbitrary return lookup variable name when using lookups for function-like mixins.
3. Other?
Anything else outstanding from this thread not implemented or resolved?
matthew-dean commentedon Jul 3, 2018
Relating to
#2, I think.add(10px, 10px)[]would be fine. Instead of "last value of name x wins" it's "last value of unnamed value (all) wins".rjgotten commentedon Jul 3, 2018
[]works for me.It avoids the problem where mixin consumers need to be aware of the internals, i.e. the variable name holding the return value.
matthew-dean commentedon Jul 3, 2018