[antlr-interest] Value types - can't be set to null in C#

Shawn Poulson spoulson3 at yahoo.com
Mon Jan 7 08:14:21 PST 2008


Hello,

Now that I've gotten setup on using ANTLR, I found a small snag that
doesn't seem to be mentioned in the Wiki or Google for that matter.

I'm building a grammar that parses a datetime string and returns a
DateTime object in C#.  So far the grammar looks like:

----- 8< ----- 8< -----
prog: dt=datetime {Debug.WriteLine("datetime=" +
$dt.value.ToString());};

datetime returns [DateTime value]:
   (h=hour24 {Debug.WriteLine("hour24=" + $h.value.ToString());}
   ':' m=minute {Debug.WriteLine("minute=" + $m.value.ToString());}
   ':' s=second {Debug.WriteLine("second=" + $s.value.ToString());}
   '.' ms=millisecond {Debug.WriteLine("millisecond=" +
$ms.value.ToString());})
   {
      $value = new DateTime(2008, 1, 4, $h.value, $m.value, $s.value,
$ms.value);
   };
      

hour24 returns [int value]:
   INT {$value = int.Parse($INT.text);};

minute returns [int value]:
   INT {$value = int.Parse($INT.text);};

second returns [int value]:
   INT {$value = int.Parse($INT.text);};

millisecond returns [int value]:
   INT {$value = int.Parse($INT.text);};

INT: '0'..'9'+;
WS: (' '|'\t'|'\r\n'|'\r')+ { $channel = HIDDEN; };
----- 8< ----- 8< -----

It generates ok with ANTLR, but when I compile in Visual Studio 2005 I
get two identical errors for "prog" and "datetime" rules:

"Cannot convert null to 'System.DateTime' because it is a value type"

One of the offending lines is:
---- 8< ----- 8< -----
    public void prog() // throws RecognitionException [1]
    {   
        DateTime dt = null;
...
---- 8< ----- 8< -----

Is there a way I can set the initialization to be something arbitrary,
like DateTime.Now?

Thanks.

---
Shawn Poulson
spoulson at explodingcoder.com


More information about the antlr-interest mailing list