Saturday, May 30, 2009

Java Riddle

I change the value of a constant in one file, and it causes a compile error in a different file. How is this possible?

Sunday, May 17, 2009

It's all C's fault

C's type casting syntax creates a lot of trouble for parsers.


What does the above code mean? are you casting negative b to type a? or are you subtracting b from a? It's ambiguous and depends on whether a is a type or a value.

Well, actually that's not the whole story. In Java, the only two ambiguous binary/unary operators are + and - which are only applicable as unary operators to primitive types. So any instance of (___)-b could be disambiguated by whether or not the ___ was one of the 7 primitive types. This is because you can't cast a primitive to anything but another primitive. In C++ this is not the case.

C++ has operator overloading, but barely dodges the bullet by enforcing the prototyping rule. To paraphrase, "every identifier must be defined prior to its usage." including types and where "prior" refers to position in source code. So if the C++ parser is traveling forward, it will have an accurate bank of identified types whenever it needs to disambiguate code such as (a)-b. All it needs to do is look up what category a belongs to--type, variable, function, etc,--and it will be able to make the right decision from there.

C++ can't cleanly separate parsing from semantic analysis, but C++ sucks anyway so who cares.

Wednesday, May 13, 2009

Java's "protected" access fine print

In Java, protected means that subclasses have access, even if the classes are in different packages. This is actually not always the case. Right from Java's language spec:

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

The following code produces a compile error.

package p1;

public class C1
protected void foo()


package p2;

import p1.C1;

public class C2 extends C1
private C1 c1;
private void bar()
{; // compile error

I have yet to understand why this is the case. I'm guessing it has something to do with virtual methods and identifier resolution tokens.

Sunday, May 3, 2009

Name that regex

What do these regular expressions match?

  1. /0x[0-9A-Fa-f]+/

  2. /\-?\d+/

  3. /\/{2}.*?\n|\/\*.*?\*\//

  4. /<!\-{2}.*?\-{2}>/

  5. /^\d{5}(\-\d{4})?$/

  6. /[A-Za-z_][A-Za-z0-9_]*/