Home
Mars Saxman's Friends
 
[Most Recent Entries] [Calendar View] [Friends View]

Below are the most recent 25 friends' journal entries.

    [ << Previous 25 ]
    Thursday, July 9th, 2009
    ericlippertatom 2:11p
    Iterator Blocks, Part One

    There is a constant tension in language design between solving general problems and solving specific problems; finding the right spot on the general-to-specific spectrum can be quite tricky.

    The design of iterator blocks yields (ha ha) a germane example. At almost every step along the way, there are opportunities for making choices that determine whether a more general or a more specific problem is being solved.

    Let’s start with the high-level design of the feature. Iterator blocks are, as the name implies, all about making it easier to write code that iterates over some collection of items in a natural way. This is a pretty darn general scenario; there are lots of potential collections (stacks, queues, lists, dozens of different kinds of trees…) containing arbitrarily many different types of items, and lots of ways to iterate over them (in order, post order, pre order, filtered, projected, grouped, sorted…)

    We could have made it much more general. Our iterator blocks can be seen as a weak kind of coroutine. We could have chosen to implement full coroutines and just made iterator blocks a special case of coroutines. And of course, coroutines are in turn less general than first-class continuations; we could have implemented continuations, implemented coroutines in terms of continuations, and iterators in terms of coroutines.

    But we didn’t. We decided that the sweet spot for the high-level scenario-driven design of the feature was iterators over collections, and so we concentrated on that. Some adventurous people use the fact that iterators are “poor-man’s coroutines” as a shortcut to building coroutine-like systems that have only a tenuous connection to the semantics of iterating over the items in a collection, but those are the exception, not the rule. Their scenarios certainly did not drive the design of the feature.

    We want to balance the generality of the feature against the high cost of that generality. Premature optimization is often cited as the root of all evil, but I don’t think that’s quite true. Premature generality is responsible for a lot of evil too! As we’ll see, a lot of the time when faced with a design decision we take the YAGNI position; we choose to implement a little bit less generality to get a large cost savings, with the assumption that hardly anyone would benefit from that spending.

    Over our next few fabulous adventures in coding I’ll discuss some of the reasons for the seemingly odd restrictions on the generality of iterator blocks – things like, why can there be no unsafe code in iterator blocks? Why can an iterator block not take a ref or out parameter? Why can’t you put a yield in a finally? And so on.

    redecho_m 5:50p
    July 9, 2009

    Fascinating long-form email post called my evolution as a programmer: mostly about the author’s progress through programming concepts and the process by which he developed abstract thinking about software development.

    Tuesday, July 7th, 2009
    _harlequin_
    12:28p
    I realized that the reason why everyone here rudely parks up your ass when stopped at traffic lights on hills, is because automatic transmissions are so much the default here that many people are just unaware of the risk that a manual can roll backwards slightly when the light turns green. You don't need to know this to get your license, and many people have simply never driven stick.
    (And because drivers here are thus obliviously giving zero margin for error, I use the hand-brake religiously, far more so than I ever needed to in NZ :-)

    Realizing how dominant the automatic is here caused me to also realize that when stopped at lights, it's pretty easy to tell who ahead of you is driving with which transmission, from how their brake lights operate. (It depends on the situation of course, but generally, an automatic can't be stationary without a foot on the brake pedal, so the brake-lights will never go off until the instant the car starts moving again. Whereas on a horizontal road, it is common for a manual to release the brakes, and when on a hill, the need for a hand-brake-start makes it likely that the brake-lights will go off before the car starts moving, because the hand-brake does not illuminate the brake-lights.)

    Around here, you don't often see a stationary car with the engine running and the brake-lights off.
    dirtylibrarian
    8:30a
    jennaxide
    7:53a
    Counter offer
    Last night Operation Victorian got together to go over Tenants in Common agreements and pocky faxed pages of the counter offer from the seller, who is currently vacationing in Maui. Their offer isn't jump-up-and-down awesome but it is workable, so we got down to nitty gritty with the real estate agent and loan officer and put hiring lawyers on deck. This has been a roller coaster of a-ha! moments, exploring homes, giddy laughter, building trust and sharing whiskey and getting happier than I ever thought I would about included washers and dryers. It also included no small amount of dread and anxiety about assuming this kind of responsibility again, where I want to go in the next few years, and fast emotional evaluation of why I want this. Hell, this time last week I was backing out because I couldn't see a way to make it work. I was tired last night and so perhaps my sense of humor was dulled, but Leslie's right: anyone that buys right now is going to look like a genius. We decided to sleep on it and make a decision whether or not to take the offer this morning.

    The house is beautiful: a lovingly restored 1908 Folk Victorian that is cut like a huge single family home but by virtue of zoning and a tidy kitchen on the second floor is a legal duplex. Chris and Leslie will take the elaborate, open first floor and I will take the two-bedroom second. It has 10 foot ceilings throughout, gorgeous fir floors and claw foot tubs in both units. It includes details like stained glass and curved ceilings. I've never really approached Victorian-style homes, I've always like Craftmans, but what the hell? Every yuppie in Wallingford has a Craftman. I love the style and it fits. The house is in fantastic repair and includes new appliances and recently rewired electrical. It's on top of Beacon Hill and from my bedroom window I can see the Cascade Mountains. It's a half mile from the Beacon Hill Light Rail station and incredibly centrally located. We are well within stumbling distance from my beloved Stronghold or from Whaya's. Chris, Leslie and I agree on a lot of things from pets to gardening to emergency planning that includes Burning Man. By the end of the night I drove home and found myself grinning involuntarily.

    I fell asleep wishing I could see the place again. Was there a shower in the upstairs, or just a tub? What's that thing on the fireplace? What the heck am I going to do with two bedrooms? And an oven! I'll have an oven! My mind is spinning. I am bracing for the work ahead-- inspection, closing the deal, moving, finding a roommate for Rusty, all within the week we leave for Burning Man. Whee!



    Current Mood: excited
    Monday, July 6th, 2009
    ericlippertatom 1:29p
    Color Color

    Pop quiz: What does the following code do when compiled and run?

    class C
    {
        public static void M(string x)
        {
            System.Console.WriteLine("static M(string)");
        }
        public void M(object s)
        {
            System.Console.WriteLine("M(object)");
        }
    }
    class Program
    {
        static void Main()
        {
            C c = new C();
            c.M("hello");
        }
    }

    (1) writes static M(string)
    (2) writes M(object)
    (3) uh, dude, this code doesn’t even compile much less run
    (4) something else

    Think about that for a bit and then try it and see if you were right.

    .

    .

    .

    .

    .

    .

    .

    In option (1), the compiler could decide that the best match is the static one and let you call it through the instance, ignoring the instance value. In option (2), the compiler could decide that the object version is the best match and ignore the static one, even though the argument match is better. But neither of those actually happens; the rules of C# say that the compiler should pick the best match based on the arguments, and then disallow static calls that are through an instance! The actual result here is therefore (3):

    error CS0176: Member 'C.M(string)' cannot be accessed with an instance reference; qualify it with a type name instead

    What is up with this craziness? If you believe that the rule “static methods should never be accessed through instances” is a good rule – and it seems reasonable – then why doesn’t overload resolution remove the static methods from the candidate set when called through an instance? Why does it even allow the “string” version to be an applicable candidate in the first place, if the compiler knows that it can never possibly work?

    I agree that this seems really goofy at first.

    To explain why this is not quite as dumb as it seems, consider the following variation on the problem. Class C stays the same.

    class B
    {
      public C C = new C();
      public void N()
      {
          C.M("hello");
      }
    }

    What does a call to N on an instance of B do?

    (1) writes static M(string)
    (2) writes M(object)
    (3) compilation error
    (4) something else

    .

    .

    .

    .

    .

    .

    A bit trickier now, isn’t it? Does C.M mean “call instance method M on the instance stored in this.C?” or does it mean “call static method M on type C”? Both are applicable!

    Because of our goofy rule we do the right thing in this case. We first resolve the call based solely on the arguments and determine that the static method is the best match. Then we check to see if the “receiver” at the call site can be interpreted as being through the type. It can. So we make the static call and write “static M(string)”. If the instance version had been the best match then we would successfully call the instance method through the property.

    So the reason that the compiler does not remove static methods when calling through an instance is because the compiler does not necessarily know that you are calling through an instance. Because there are situations where it is ambiguous whether you’re calling through an instance or a type, we defer deciding which you meant until the best method has been selected.

    Now, one could make the argument that in our first case, the receiver cannot possibly be a type. We could have further complicated the language semantics by having three overload resolution rules, one for when the receiver is known to be a type, one for when the receiver is known to not be a type, and one for when the receiver might or might not be a type. But rather than complicate the language further, we made the pragmatic choice of simply deferring the staticness check until after the bestness check. That’s not perfect but it is good enough for most cases and it solves the common problem.

    The common problem is the situation that arises when you have a property of a type with the same name, and then try to call either a static method on the type, or an instance method on the property. (This can also happen with locals and fields, but local and field names typically differ in case from the names of their types.) The canonical motivating example is a public property named Color of type Color, so we call this “the Color Color problem”.

    In real situations the instance and static methods typically have different names, so in the typical scenario you never end up calling an instance method when you expect to call a static method, or vice versa. The case I presented today with a name collision between a static and an instance method is relatively rare.

    If you’re interested in reading the exact rules for how the compiler deals with the Color Color problem, see section 7.5.4.1 of the C# 3.0 specification.

    jennaxide
    1:03p
    Predictor
    Wow. I just found an entry from January 2007 that I wrote about the upcoming election:
    "
    Senator Barack "Rock You Like a 109th Congress Hurricane" Obama has "announced that he is forming an Exploratory Committee with view to challenge for the Democratic Presidential Nomination." this makes the two Democratic frontrunners a woman Senator from Arkansas and a mulitracial Senator originally from Hawai'i. pretty boy Johnny Edwards, whom i broke up with in my heart after Dick Cheney spanked him like a little girl in the 2004 Presidential debates, has got a challenge of Sisyphusian proportions on his hands with these two popularity contest winners competing for the Democratic nomination. he's in last place behind Al Gore, who hasn't announced that he is running. but for that matter, neither has presumed leader Hillary.

    Obama is one charismatic fella, that's for sure, and definitely the strongest minority potential presidential candidate in American history. but he's a sophomore politician with some utopian ideas and he voted for the fence (see rant here). Hillary tends to talk out of both sides of her mouth. Edwards has the potential to really make changes, but he's such a slave to the muse i suspect the political machine will chew him up and spit him out. and good old Al. $5 says he doesn't even run.
    "


    Current Mood: huh
    Current Music: Middle Cyclone- Neko Case
    velvetgarden
    12:32p
    More photos!
    The photographer just sent me a few more photos from this shoot, so I've added them to the Flickr set.

    These are from a shoot I did back in April with ByteStudio.

    As always, click the photo to see the full set on Flickr.

    butterflake
    11:18a
    and up and even
    One of the only reasons I like Facebook so far is the easy capture of behavioral phenomena...

    Like everyone having insomnia last night.

    Or everyone being in a cranky mood. (clarification: not today specific, just an example of another day)

    etc. etc.

    Current Mood: useless today
    Saturday, July 4th, 2009
    thegudlife
    11:14p
    fuck bukowski.
    The depression is here although the govt. prefers to call it a “recession.” Which reminds me of the old one: a recession is when your friends are out of jobs, a depression is when you’re out of one. It’s at times like this that I’m glad that I trained myself throughout a lifetime to detest a job of any sort. All these poor automobile workers sitting around glassy-eyed with homes half-paid for and cheating wives. They trusted that a hard day’s work for a good day’s pay would get them through. Now as the govt. tries to pump blood into the corpse they sit around and work crossword puzzles and look at daytime TV shows programmed to the female…the only thing that will cure this is the same thing that has cured every capitalistic depression since 1940 – another war; a big war, a little war, a hot war, a cold war, but war war war, and so we arm the Arabs and we arm the Jews and we send scout planes out once again to Vietnam, and I write my poems and drink my beer and try to get through the last 4 scenes in Factotum[.]

    Charles Bukowski
    Feb 19, 1975


    You know what? Fuck you Bukowski. Fuck your faulty logic. My grandparents, both Jews, my great aunts and uncles, killed by the nazis, want to be armed and killing people? Fuck you and the horse you road in on.

    Oh. and all the daytime tv shows programed to the female? fuck you for lumping me and my daytime shows in with your fat, lazy, ghoulish government.

    FUCK YOU.
    thegudlife
    10:53p
    more than this is nothing
    I declare my independence to enjoy life. Making cookies drinking wine sleeping exploring. I learned to enjoy life in 2002 (oddly enough, at brc. very coincidental). I look forward to more of it.
    jennaxide
    9:08a
    In the rabbitat at Chez NA
    A fine thing, is a bunneh.

    Jenna & Tomoe

    More here and here


    Current Mood: happy
    Current Music: People Got a Lotta Nerve- Neko Case
    Friday, July 3rd, 2009
    jennaxide
    11:32a
    Nature of the beast
    Ursula and I are holding the couch down with skill and panache, as we spent another delightful evening laughing late around the fire with my Stronghomies. Yesterday afternoon I jumped out of work a little early for a last-minute meeting. Chris, Leslie and I are setting gears in motion that change our collective direction in some fun-as-hell exciting ways, and true to our playful grown up characters we set off the legally binding stack of dominoes with an old-fashioned rochambeau. Leslie won. And no, you don't get any details. Mysterious Jenna is mysterious. Anyway I'll find out on my birthday if this penguin will fly.

    I headed up to Highland Park for Thursday night pickleball and squeezed in a few games with my handsome fella and our pals. I love the Zero Thousand crew with a respect and joy for kamakazi creativity and wit, balanced with more playful grown up characters and an appreciation for whiskey. We trooped out to the West Seattle junction where I redeemed my six-year-old free cd card at Easy Street for the new Neko Case (yay!), then tucked in to a delicious Indian dinner. As usual the table conversation careened around like a hilarious pinball between throat singing, Transformers, goat on the bone and tales of urban home-ownership.

    Feeling kinda like a deadbeat cat owner I headed home, and was happily surprised by a fire in the courtyard and a heated debate about the changing face of Georgetown culture. Then it was Randy, Gabe, and I and the bottom of the case of Tecate when who comes through the gate but Chris and Leslie! Pretty soon there was hula hooping, Ursula on a leash with us, the beautiful embrace of bluegrass in the digital age, riotous laughing and by one AM plots had been hatched for a traveling carnival complete hoops, stilts and fire and Georgetown pub crawl (well, pub lurch, anyway) on converted buses. Since the moment was right I cracked open the delicious bottle of beer Nathan gave me last November for my housewarming when I came to live at Stronghold and we shared it all around. Today my head may be ringing like a bell but my heart is overflowing with shenanigans and promise.

    Current Mood: happy
    Current Music: The Next Time You Say "Forever" - Neko Case
    Thursday, July 2nd, 2009
    butterflake
    3:11p
    ericlippertatom 2:10p
    The correct answer is "no"

    No technology today. I have not done a post on relationship advice in ages!

    Compare and contrast these two conversations:

    ******

    Version One:

    Alice: Thanks for having lunch with me. I suppose you know what I want to talk about.

    Eric: Yeah, I do. I think you shouldn't jump to conclusions solely on the basis of all the rumours that are going around. There are any number of perfectly innocent reasons why Bob and Eve could have been seen together at Chez Franch together last month.

    Alice: What?!

    Eric: Huh?

    Alice: First she intercepts my email, then she steals my boyfriend?!? Passive attacker my eye!

    This conversation, already off to a bad start, is not going to get any better.

    ******

    Version Two:

    Alice: Thanks for having lunch with me. I suppose you know what I want to talk about.

    Eric: No, I do not.

    Alice: I was hurt that you didn't invite me to the book signing.

    Eric: I did invite you to the book signing. Check your spam filter.

    Alice: [boot laptop, search email...] Ah. Yes you did invite me. And I see your new book is called "Make Money Fast With Nigerian Viagra"; did anyone actually get the invitation?

    Eric: Hmm, that might explain the low turnout.

    ******

    Important human relationship safety tip: the correct answer to "do you know what I am thinking?" is "no". Remember, there are at least two thick slabs of bone between your brain and everyone else's brain. Those thick slabs of bone impede telepathy.

    butterflake
    12:03p
    because that's what I needed...
    I twisted my knee, rather badly. I am lame, as of Tuesday night.

    Yesterday I spent the day watching Dexter, the Dark Crystal, True Blood, and the Juniper Tree, napping, and working outside, a little.

    Great progress on the sculptures, though. Two more are done (for a total of five), two more in progress and two left. I'm leaving for Critical in two weeks.

    Yikes! And of course, now I'm lame. Because THAT's what I needed right now.

    Current Mood: gimp
    kety
    11:51a
    To-do list
    1. Pick up chairs from a designer
    2. Do some errands in the 'office'
    3. Do two house blessings
    4. Tidy M's house
    5. Spend time with the girls
    6. Try not to explode with excitement because M comes home TOMORROW!!!
    Wednesday, July 1st, 2009
    animaeruption
    6:55p
    I just remembered!
    I LOVED this show as a little boy. Always I wanted to be the Little Prince when I grew up and water my rose lady and walk around upside down on my little planet and catch shooting stars in butterfly nets. Actually... I still do. EEE!!!

    Anyone else think this was cool?

    velvetgarden
    4:33p
    Photo party - round 2!


    Photo party - round 2! We got great response to the photo party event on Saturday, but it was such a busy weekend that a lot of people couldn't make it. So we're doing it again for this week's Pioneer Square Artwalk on Thursday night! (and Friday is a holiday!)

    Here are the details:

    Artwalk Photo Party / Fundraiser
    Thursday, July 2, 2009
    7 - 10 pm
    Studio Brick
    214 1st Ave S (Grand Central Building, lower level)
    Seattle, WA

    Thomas and I are hosting a photo party / wine gala / Burning Man art project fundraiser. We hope you can join us!

    If you need professional photos for any kind of promotion, or just want a portrait - this event is for you! Or if you'd like to relax with some friends, and enjoy some good wine before heading to your evening plans, please stop by!

    A donation of as little as $20 gives you a mini photo session in a professionally-equipped photo studio. To see some examples of Thomas's photography, check out his Model Mayhem portfolio.

    To RSVP, or to get more information about the photo party and the art project, please click here: http://www.facebook.com/event.php?eid=116448195959&ref=mf
    redecho_m 10:33p
    Changes

    It has been a challenging year, and I feel drained. I’m glad to have friends who can support me through rough times, but it’s time I got my life back to a more peaceful state; time for a change in focus.

    I moved to a new house last weekend. It’s a pretty, comfortable, welcoming little place, a 1910-era Craftsman on the eastern side of Capitol Hill - not far from where I’ve been living, but closer to shops and friends and activity. Cat moved in a couple of weeks ago, and Sam will be joining us at the end of the month; the house is maybe half the size of the one I’ve been living in, but there’s plenty of room for three.

    The upper floor of this house was designed as a master suite; it’s a sprawling big room with two closets and funky ceiling angles. I’m going to cozy off a little nook to use as a bedroom and turn the rest into an art studio. I feel good when I make things, even more so when I can share them with people who will enjoy them, so I want to arrange my living space around that. I imagine a “clean” work table for sewing, a “dirty” workbench for electronics and general fabrication, a desk with computer and electronic music hardware, cabinets full of tools, a whole closet full of materials and stored projects…

    I’ve also given notice at Microsoft. This job has been a frustrating, difficult experience from beginning to end; I kept on struggling through, at first because I thought it was just an unusually difficult adaptation period, then because I couldn’t imagine where else my career could go, and ultimately because I simply didn’t want to abandon an unfinished project. The project is almost over now, and I still don’t know exactly what my next career step will be, but I’ve seen enough to be certain that this job will never offer the kind of work I need - nor, it is clear, are my skills or temperament particularly well suited to the group’s needs. I’ll spend the next couple of weeks wrapping up a few last bugs, writing some design documents, and passing on what little there is to know about the feature I’ve been grinding my way through - then I’m out of here, glad to be done with the Eastside and ready to enjoy the summer.

    I don’t know what I’ll do next, but there are a handful of options in the air already, and I have a good long while to figure it out. I’d like to find something a bit more low-key - perhaps another telecommuting position - something I can do well without having to pour all of my free time into it. In the meantime I will probably spend a fair bit of time working on the Groovik’s Cube and riding around on my motorcycle, enjoying the sunshine.

    kety
    12:32p
    Who wears the pants around here?
     I have a sneaking suspicion that Zoro is training ME rather than the other way around.  Lately, I've noticed that when he wants something, he sits right in front of it.  Today I fed him a bit late and instead of whining, he just sat by his food dish and stared at me.  I fed him.  About 20 minutes later, he sat in front of the door to his kitty box and stared at me.  I cleaned out the cat box and he promptly went in there and did his thing.  

    He has now ceased pestering/starting at me and is napping happily on my bed (boy will he be sad when M comes home...no more kitty in the bedroom).  

    Speaking of which, he's taken to sleeping UNDER the covers.  I coudln't find him yesterday but saw a little Zoro sized lump under my covers.  I poked it.  It started purring and then I lifted up the covers to find a cute little kitten morsel nuzzled up in perfect circular nap position.  So cute.

    Kitten lump:



    Kitten morsel revealed!:



     
    jennaxide
    10:48a
    OKLAHOMA CITIZEN'S PROCLAMATION FOR NOT TAKING SALLY KERN SERIOUSLY
    This made my day.

    "We the People of Oklahoma, Invoking the guidance of basic reason and logic, in order to prevent that vein in our foreheads from popping out; to secure a state government that is merely corrupt rather than criminally insane; to promote our mutual Welfare and Happiness, do establish this proclamation and call upon the people of the great State of Oklahoma, and our fellow Patriots in these United States of America who look to non Gaylord owned media for guidance, to acknowledge the need for Sally Kern to step out of the spotlight for a while and mutter gently to her handgun...."

    The rest of the hilarious text this-a way.

    "...NOW THEREFORE, BE IT RESOLVED that we the undersigned snarky bastards, appealing to the basic decency and reasonableness of our fellow citizens, solemnly declare that the HOPE of the great State of Oklahoma and of these United States, rests upon politicians and civil servants who care more about their constituents than about the 15 or so votes to be gained by showboating and being self righteous..."



    In response to the absurd Morality Proclamation.



    Current Mood: amused
    Current Music: If I Didn't Care- Billy Holiday
    jennaxide
    7:08a
    Home repair
    Houses, houses. It seems I always dream of houses. Last night I dreamed that Leslie discovered a huge empty space behind the shower wall. She was upset about it and thought it was going to be expensive to fix. I was worried when she told me there was a problem with the shower, that we were going to have to deal with soggy tile and rotten drywall, but when I saw the space it didn't seem hard to correct at all. This is something we could handle.

    On the other hand, when did I start dreaming about grown up things? Where are the bath houses full of living statues and talking toucans of my youth?
    Tuesday, June 30th, 2009
    jennaxide
    1:33p
    Note to self
    Stop it. Touching molten metal-- though yes, it is cooling-- still hurts. So keep your damn nose out of it already. You have better things to do, like being brave, like playing ball, and like being smart to catch this opportunity tiger by the tail.

    Current Mood: determined
    Monday, June 29th, 2009
    ericlippertatom 2:30p
    The void is invariant

    [UPDATES below] 

    A while back I described a kind of variance that we’ve supported since C# 2.0. When assigning a method group to a delegate type, such that both the selected method and the delegate target agree that their return type is a reference type, then the conversion is allowed to be covariant. That is, you can say:

    Giraffe GetGiraffe() { … }

    Func<Animal> f = GetGiraffe;

    This works logically because anyone who calls f must be able to handle any animal that comes back. The actual method claims to only return animals, and in fact, makes the stronger claim to only return giraffes.

    This works out in the CLR because the bits that make up a reference to an instance of Giraffe are exactly the same bits that make up a reference to that Giraffe interpreted as an instance of Animal. We can allow this magical conversion to happen because the CLR guarantees that it will all just work out without going in there and having to futz around with the bits.

    This is why this trick only works with reference types. A method that returns, say, a double cannot be converted via a covariant conversion to a delegate type that expects the method to return an object. Somewhere there would have to be code emitted that takes the returned double and boxes it to object; the bits of a double and the bits of a reference to an object boxing a double are completely different.

    But why doesn’t this trick work with void types? Here we have a method that returns some sort of success or failure code. Maybe we don’t care what it returns.

    static bool DoSomething(bool b)
    {
      if (b) return DoTheThing();
      else return DoTheOtherThing();
    }

    Action<bool> action = DoSomething;

    This doesn’t work. Why not? The caller of the action is not even going to use the returned value, so it doesn’t matter one bit what it is! Shouldn’t “void” be considered a supertype of all possible types for the purposes of covariant return type conversions from method groups to delegate types?

    No, and I’ll tell you why.

    Consider what happens when you do this:

    bool x = DoSomething(true);

    We spit out IL that does the following:

    (1) put true on the IL stack – the stack gets one deeper
    (2) call DoSomething – the argument is removed from the stack and the return value is placed on the stack.  Net, the stack stays the same size as before
    (3) stuff whatever on top of the stack into local variable x – the stack now returns to its original depth.

    Now consider what happens when you do this:

    DoSomething(true);

    We spit out IL that does the first two steps as before. But we cannot stop there! There is now a bool on the IL stack which needs to be removed. We generate a pop instruction to represent the fact that the returned bool has been discarded.

    Now consider what happens when you do this:

    action(true);

    The compiler believes that action is a void-returning method, so it does not generate a pop instruction. If we allowed you to stuff DoSomething into the action, then we would be allowing you to misalign the IL stack!

    But didn’t I say “the stack is an implementation detail?” Yes, but that’s a different stack. The CLI specification describes a “virtual machine” which passes around arguments and returned values on a stack. An implementation of the CLI is required to make something that behaves like the specified machine, but it is not required to do so in any particular manner. It is not required to use the million-bytes-per-thread stack supplied to each thread by the operating system as its implementation of the IL stack; that’s a convenient structure to use, of course, but it’s an implementation detail that it does so.

    (As an aside: when we implemented the script engines, we also first specified our own private stack-based virtual machine. When we implemented it, we decided to put the information about “return addresses” – that is, “what code do I run next?” on the system stack, but we put arguments and return values of script functions in a stack-shaped block of memory that we allocated on our own. This made building the JScript garbage collector easier.)

    In practice, the jitter uses the system stack for some things and registers for other things. Return values are actually often sent back in a register, not on the stack. But that implementation detail doesn’t help us out when deciding what the conversion rules are; we have to assume that the implementation can do no more than what the CLI specification says. Had the CLI specification said “the returned value of any function is passed back in a ‘virtual register’” rather than having it pushed onto the stack, then we could have made void-returning delegates compatible with functions that returned anything. You can always just ignore the value in the register. But that’s not what the CLI specified, so that’s not what we can do.

    [UPDATE]

    A number of people have asked in the comments why we do not simply generate a helper method that does what you want. That is, when you say

    Action<bool> action = DoSomething;

    realize that as

    static void DoSomethingHelper(bool b)
    {
       bool result = DoSomething(b); // result is ignored
    }
    ...
    Action<bool> action = DoSomethingHelper;

    We could do that. But where would you like the line to be drawn? Should you be able to assign a reference to a method that returns an int to a Func<Nullable<int>>? We could spit a helper method that converts the int to a nullable int. What about Func<double>? We could spit a helper method that converts the int to a double. What about Func<object>? We could spit a helper method that boxes the int, unexpectedly allocating memory off the heap every time you call it. What about a Func<Foo> where there is a user-defined implicit conversion from int to Foo?

    We could be spitting arbitrarily complex fixer-upper methods that would seamlessly "do what you meant to say", and we have to stop somewhere. The exact semantics of what we do and do not fix up would have to be designed, specified, implemented, tested, documented, shipped to customers and maintained forever. Those are costs. Plus, every time we add a new conversion rule to the language we add breaking changes. The costs of those breaking changes to our customers have to be factored in.

    But more fundamentally, one of the design principles of C# is "if you say something wrong then we tell you rather than trying to guess what you meant". JScript is deliberately a "muddle on through and do the best you can" language; C# is not. If what you want to do is make a delegate to a helper method then you express that intention by going right ahead and making that method.

    [ << Previous 25 ]
Red Echo   About LiveJournal.com

Advertisement