Fix null sessions in HttpContextWrapper.Session
[mono.git] / mcs / class / Mono.Options / Mono.Options / Options.cs
1 //
2 // Options.cs
3 //
4 // Authors:
5 //  Jonathan Pryor <jpryor@novell.com>
6 //  Federico Di Gregorio <fog@initd.org>
7 //
8 // Copyright (C) 2008 Novell (http://www.novell.com)
9 // Copyright (C) 2009 Federico Di Gregorio.
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 // Compile With:
32 //   gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
33 //   gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
34 //
35 // The LINQ version just changes the implementation of
36 // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
37
38 //
39 // A Getopt::Long-inspired option parsing library for C#.
40 //
41 // NDesk.Options.OptionSet is built upon a key/value table, where the
42 // key is a option format string and the value is a delegate that is 
43 // invoked when the format string is matched.
44 //
45 // Option format strings:
46 //  Regex-like BNF Grammar: 
47 //    name: .+
48 //    type: [=:]
49 //    sep: ( [^{}]+ | '{' .+ '}' )?
50 //    aliases: ( name type sep ) ( '|' name type sep )*
51 // 
52 // Each '|'-delimited name is an alias for the associated action.  If the
53 // format string ends in a '=', it has a required value.  If the format
54 // string ends in a ':', it has an optional value.  If neither '=' or ':'
55 // is present, no value is supported.  `=' or `:' need only be defined on one
56 // alias, but if they are provided on more than one they must be consistent.
57 //
58 // Each alias portion may also end with a "key/value separator", which is used
59 // to split option values if the option accepts > 1 value.  If not specified,
60 // it defaults to '=' and ':'.  If specified, it can be any character except
61 // '{' and '}' OR the *string* between '{' and '}'.  If no separator should be
62 // used (i.e. the separate values should be distinct arguments), then "{}"
63 // should be used as the separator.
64 //
65 // Options are extracted either from the current option by looking for
66 // the option name followed by an '=' or ':', or is taken from the
67 // following option IFF:
68 //  - The current option does not contain a '=' or a ':'
69 //  - The current option requires a value (i.e. not a Option type of ':')
70 //
71 // The `name' used in the option format string does NOT include any leading
72 // option indicator, such as '-', '--', or '/'.  All three of these are
73 // permitted/required on any named option.
74 //
75 // Option bundling is permitted so long as:
76 //   - '-' is used to start the option group
77 //   - all of the bundled options are a single character
78 //   - at most one of the bundled options accepts a value, and the value
79 //     provided starts from the next character to the end of the string.
80 //
81 // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
82 // as '-Dname=value'.
83 //
84 // Option processing is disabled by specifying "--".  All options after "--"
85 // are returned by OptionSet.Parse() unchanged and unprocessed.
86 //
87 // Unprocessed options are returned from OptionSet.Parse().
88 //
89 // Examples:
90 //  int verbose = 0;
91 //  OptionSet p = new OptionSet ()
92 //    .Add ("v", v => ++verbose)
93 //    .Add ("name=|value=", v => Console.WriteLine (v));
94 //  p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
95 //
96 // The above would parse the argument string array, and would invoke the
97 // lambda expression three times, setting `verbose' to 3 when complete.  
98 // It would also print out "A" and "B" to standard output.
99 // The returned array would contain the string "extra".
100 //
101 // C# 3.0 collection initializers are supported and encouraged:
102 //  var p = new OptionSet () {
103 //    { "h|?|help", v => ShowHelp () },
104 //  };
105 //
106 // System.ComponentModel.TypeConverter is also supported, allowing the use of
107 // custom data types in the callback type; TypeConverter.ConvertFromString()
108 // is used to convert the value option to an instance of the specified
109 // type:
110 //
111 //  var p = new OptionSet () {
112 //    { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
113 //  };
114 //
115 // Random other tidbits:
116 //  - Boolean options (those w/o '=' or ':' in the option format string)
117 //    are explicitly enabled if they are followed with '+', and explicitly
118 //    disabled if they are followed with '-':
119 //      string a = null;
120 //      var p = new OptionSet () {
121 //        { "a", s => a = s },
122 //      };
123 //      p.Parse (new string[]{"-a"});   // sets v != null
124 //      p.Parse (new string[]{"-a+"});  // sets v != null
125 //      p.Parse (new string[]{"-a-"});  // sets v == null
126 //
127
128 using System;
129 using System.Collections;
130 using System.Collections.Generic;
131 using System.Collections.ObjectModel;
132 using System.ComponentModel;
133 using System.Globalization;
134 using System.IO;
135 using System.Runtime.Serialization;
136 using System.Security.Permissions;
137 using System.Text;
138 using System.Text.RegularExpressions;
139
140 #if LINQ
141 using System.Linq;
142 #endif
143
144 #if TEST
145 using NDesk.Options;
146 #endif
147
148 #if NDESK_OPTIONS
149 namespace NDesk.Options
150 #else
151 namespace Mono.Options
152 #endif
153 {
154         static class StringCoda {
155
156                 public static IEnumerable<string> WrappedLines (string self, params int[] widths)
157                 {
158                         IEnumerable<int> w = widths;
159                         return WrappedLines (self, w);
160                 }
161
162                 public static IEnumerable<string> WrappedLines (string self, IEnumerable<int> widths)
163                 {
164                         if (widths == null)
165                                 throw new ArgumentNullException ("widths");
166                         return CreateWrappedLinesIterator (self, widths);
167                 }
168
169                 private static IEnumerable<string> CreateWrappedLinesIterator (string self, IEnumerable<int> widths)
170                 {
171                         if (string.IsNullOrEmpty (self)) {
172                                 yield return string.Empty;
173                                 yield break;
174                         }
175                         using (IEnumerator<int> ewidths = widths.GetEnumerator ()) {
176                                 bool? hw = null;
177                                 int width = GetNextWidth (ewidths, int.MaxValue, ref hw);
178                                 int start = 0, end;
179                                 do {
180                                         end = GetLineEnd (start, width, self);
181                                         char c = self [end-1];
182                                         if (char.IsWhiteSpace (c))
183                                                 --end;
184                                         bool needContinuation = end != self.Length && !IsEolChar (c);
185                                         string continuation = "";
186                                         if (needContinuation) {
187                                                 --end;
188                                                 continuation = "-";
189                                         }
190                                         string line = self.Substring (start, end - start) + continuation;
191                                         yield return line;
192                                         start = end;
193                                         if (char.IsWhiteSpace (c))
194                                                 ++start;
195                                         width = GetNextWidth (ewidths, width, ref hw);
196                                 } while (start < self.Length);
197                         }
198                 }
199
200                 private static int GetNextWidth (IEnumerator<int> ewidths, int curWidth, ref bool? eValid)
201                 {
202                         if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) {
203                                 curWidth = (eValid = ewidths.MoveNext ()).Value ? ewidths.Current : curWidth;
204                                 // '.' is any character, - is for a continuation
205                                 const string minWidth = ".-";
206                                 if (curWidth < minWidth.Length)
207                                         throw new ArgumentOutOfRangeException ("widths",
208                                                         string.Format ("Element must be >= {0}, was {1}.", minWidth.Length, curWidth));
209                                 return curWidth;
210                         }
211                         // no more elements, use the last element.
212                         return curWidth;
213                 }
214
215                 private static bool IsEolChar (char c)
216                 {
217                         return !char.IsLetterOrDigit (c);
218                 }
219
220                 private static int GetLineEnd (int start, int length, string description)
221                 {
222                         int end = System.Math.Min (start + length, description.Length);
223                         int sep = -1;
224                         for (int i = start; i < end; ++i) {
225                                 if (description [i] == '\n')
226                                         return i+1;
227                                 if (IsEolChar (description [i]))
228                                         sep = i+1;
229                         }
230                         if (sep == -1 || end == description.Length)
231                                 return end;
232                         return sep;
233                 }
234         }
235
236         public class OptionValueCollection : IList, IList<string> {
237
238                 List<string> values = new List<string> ();
239                 OptionContext c;
240
241                 internal OptionValueCollection (OptionContext c)
242                 {
243                         this.c = c;
244                 }
245
246                 #region ICollection
247                 void ICollection.CopyTo (Array array, int index)  {(values as ICollection).CopyTo (array, index);}
248                 bool ICollection.IsSynchronized                   {get {return (values as ICollection).IsSynchronized;}}
249                 object ICollection.SyncRoot                       {get {return (values as ICollection).SyncRoot;}}
250                 #endregion
251
252                 #region ICollection<T>
253                 public void Add (string item)                       {values.Add (item);}
254                 public void Clear ()                                {values.Clear ();}
255                 public bool Contains (string item)                  {return values.Contains (item);}
256                 public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
257                 public bool Remove (string item)                    {return values.Remove (item);}
258                 public int Count                                    {get {return values.Count;}}
259                 public bool IsReadOnly                              {get {return false;}}
260                 #endregion
261
262                 #region IEnumerable
263                 IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
264                 #endregion
265
266                 #region IEnumerable<T>
267                 public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
268                 #endregion
269
270                 #region IList
271                 int IList.Add (object value)                {return (values as IList).Add (value);}
272                 bool IList.Contains (object value)          {return (values as IList).Contains (value);}
273                 int IList.IndexOf (object value)            {return (values as IList).IndexOf (value);}
274                 void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
275                 void IList.Remove (object value)            {(values as IList).Remove (value);}
276                 void IList.RemoveAt (int index)             {(values as IList).RemoveAt (index);}
277                 bool IList.IsFixedSize                      {get {return false;}}
278                 object IList.this [int index]               {get {return this [index];} set {(values as IList)[index] = value;}}
279                 #endregion
280
281                 #region IList<T>
282                 public int IndexOf (string item)            {return values.IndexOf (item);}
283                 public void Insert (int index, string item) {values.Insert (index, item);}
284                 public void RemoveAt (int index)            {values.RemoveAt (index);}
285
286                 private void AssertValid (int index)
287                 {
288                         if (c.Option == null)
289                                 throw new InvalidOperationException ("OptionContext.Option is null.");
290                         if (index >= c.Option.MaxValueCount)
291                                 throw new ArgumentOutOfRangeException ("index");
292                         if (c.Option.OptionValueType == OptionValueType.Required &&
293                                         index >= values.Count)
294                                 throw new OptionException (string.Format (
295                                                         c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), 
296                                                 c.OptionName);
297                 }
298
299                 public string this [int index] {
300                         get {
301                                 AssertValid (index);
302                                 return index >= values.Count ? null : values [index];
303                         }
304                         set {
305                                 values [index] = value;
306                         }
307                 }
308                 #endregion
309
310                 public List<string> ToList ()
311                 {
312                         return new List<string> (values);
313                 }
314
315                 public string[] ToArray ()
316                 {
317                         return values.ToArray ();
318                 }
319
320                 public override string ToString ()
321                 {
322                         return string.Join (", ", values.ToArray ());
323                 }
324         }
325
326         public class OptionContext {
327                 private Option                option;
328                 private string                name;
329                 private int                   index;
330                 private OptionSet             set;
331                 private OptionValueCollection c;
332
333                 public OptionContext (OptionSet set)
334                 {
335                         this.set = set;
336                         this.c   = new OptionValueCollection (this);
337                 }
338
339                 public Option Option {
340                         get {return option;}
341                         set {option = value;}
342                 }
343
344                 public string OptionName { 
345                         get {return name;}
346                         set {name = value;}
347                 }
348
349                 public int OptionIndex {
350                         get {return index;}
351                         set {index = value;}
352                 }
353
354                 public OptionSet OptionSet {
355                         get {return set;}
356                 }
357
358                 public OptionValueCollection OptionValues {
359                         get {return c;}
360                 }
361         }
362
363         public enum OptionValueType {
364                 None, 
365                 Optional,
366                 Required,
367         }
368
369         public abstract class Option {
370                 string prototype, description;
371                 string[] names;
372                 OptionValueType type;
373                 int count;
374                 string[] separators;
375
376                 protected Option (string prototype, string description)
377                         : this (prototype, description, 1)
378                 {
379                 }
380
381                 protected Option (string prototype, string description, int maxValueCount)
382                 {
383                         if (prototype == null)
384                                 throw new ArgumentNullException ("prototype");
385                         if (prototype.Length == 0)
386                                 throw new ArgumentException ("Cannot be the empty string.", "prototype");
387                         if (maxValueCount < 0)
388                                 throw new ArgumentOutOfRangeException ("maxValueCount");
389
390                         this.prototype   = prototype;
391                         this.description = description;
392                         this.count       = maxValueCount;
393                         this.names       = (this is OptionSet.Category)
394                                 // append GetHashCode() so that "duplicate" categories have distinct
395                                 // names, e.g. adding multiple "" categories should be valid.
396                                 ? new[]{prototype + this.GetHashCode ()}
397                                 : prototype.Split ('|');
398
399                         if (this is OptionSet.Category)
400                                 return;
401
402                         this.type        = ParsePrototype ();
403
404                         if (this.count == 0 && type != OptionValueType.None)
405                                 throw new ArgumentException (
406                                                 "Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
407                                                         "OptionValueType.Optional.",
408                                                 "maxValueCount");
409                         if (this.type == OptionValueType.None && maxValueCount > 1)
410                                 throw new ArgumentException (
411                                                 string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
412                                                 "maxValueCount");
413                         if (Array.IndexOf (names, "<>") >= 0 && 
414                                         ((names.Length == 1 && this.type != OptionValueType.None) ||
415                                          (names.Length > 1 && this.MaxValueCount > 1)))
416                                 throw new ArgumentException (
417                                                 "The default option handler '<>' cannot require values.",
418                                                 "prototype");
419                 }
420
421                 public string           Prototype       {get {return prototype;}}
422                 public string           Description     {get {return description;}}
423                 public OptionValueType  OptionValueType {get {return type;}}
424                 public int              MaxValueCount   {get {return count;}}
425
426                 public string[] GetNames ()
427                 {
428                         return (string[]) names.Clone ();
429                 }
430
431                 public string[] GetValueSeparators ()
432                 {
433                         if (separators == null)
434                                 return new string [0];
435                         return (string[]) separators.Clone ();
436                 }
437
438                 protected static T Parse<T> (string value, OptionContext c)
439                 {
440                         Type tt = typeof (T);
441                         bool nullable = tt.IsValueType && tt.IsGenericType && 
442                                 !tt.IsGenericTypeDefinition && 
443                                 tt.GetGenericTypeDefinition () == typeof (Nullable<>);
444                         Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
445                         TypeConverter conv = TypeDescriptor.GetConverter (targetType);
446                         T t = default (T);
447                         try {
448                                 if (value != null)
449                                         t = (T) conv.ConvertFromString (value);
450                         }
451                         catch (Exception e) {
452                                 throw new OptionException (
453                                                 string.Format (
454                                                         c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
455                                                         value, targetType.Name, c.OptionName),
456                                                 c.OptionName, e);
457                         }
458                         return t;
459                 }
460
461                 internal string[] Names           {get {return names;}}
462                 internal string[] ValueSeparators {get {return separators;}}
463
464                 static readonly char[] NameTerminator = new char[]{'=', ':'};
465
466                 private OptionValueType ParsePrototype ()
467                 {
468                         char type = '\0';
469                         List<string> seps = new List<string> ();
470                         for (int i = 0; i < names.Length; ++i) {
471                                 string name = names [i];
472                                 if (name.Length == 0)
473                                         throw new ArgumentException ("Empty option names are not supported.", "prototype");
474
475                                 int end = name.IndexOfAny (NameTerminator);
476                                 if (end == -1)
477                                         continue;
478                                 names [i] = name.Substring (0, end);
479                                 if (type == '\0' || type == name [end])
480                                         type = name [end];
481                                 else 
482                                         throw new ArgumentException (
483                                                         string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
484                                                         "prototype");
485                                 AddSeparators (name, end, seps);
486                         }
487
488                         if (type == '\0')
489                                 return OptionValueType.None;
490
491                         if (count <= 1 && seps.Count != 0)
492                                 throw new ArgumentException (
493                                                 string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
494                                                 "prototype");
495                         if (count > 1) {
496                                 if (seps.Count == 0)
497                                         this.separators = new string[]{":", "="};
498                                 else if (seps.Count == 1 && seps [0].Length == 0)
499                                         this.separators = null;
500                                 else
501                                         this.separators = seps.ToArray ();
502                         }
503
504                         return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
505                 }
506
507                 private static void AddSeparators (string name, int end, ICollection<string> seps)
508                 {
509                         int start = -1;
510                         for (int i = end+1; i < name.Length; ++i) {
511                                 switch (name [i]) {
512                                         case '{':
513                                                 if (start != -1)
514                                                         throw new ArgumentException (
515                                                                         string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
516                                                                         "prototype");
517                                                 start = i+1;
518                                                 break;
519                                         case '}':
520                                                 if (start == -1)
521                                                         throw new ArgumentException (
522                                                                         string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
523                                                                         "prototype");
524                                                 seps.Add (name.Substring (start, i-start));
525                                                 start = -1;
526                                                 break;
527                                         default:
528                                                 if (start == -1)
529                                                         seps.Add (name [i].ToString ());
530                                                 break;
531                                 }
532                         }
533                         if (start != -1)
534                                 throw new ArgumentException (
535                                                 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
536                                                 "prototype");
537                 }
538
539                 public void Invoke (OptionContext c)
540                 {
541                         OnParseComplete (c);
542                         c.OptionName  = null;
543                         c.Option      = null;
544                         c.OptionValues.Clear ();
545                 }
546
547                 protected abstract void OnParseComplete (OptionContext c);
548
549                 public override string ToString ()
550                 {
551                         return Prototype;
552                 }
553         }
554
555         public abstract class ArgumentSource {
556
557                 protected ArgumentSource ()
558                 {
559                 }
560
561                 public abstract string[] GetNames ();
562                 public abstract string Description { get; }
563                 public abstract bool GetArguments (string value, out IEnumerable<string> replacement);
564
565                 public static IEnumerable<string> GetArgumentsFromFile (string file)
566                 {
567                         return GetArguments (File.OpenText (file), true);
568                 }
569
570                 public static IEnumerable<string> GetArguments (TextReader reader)
571                 {
572                         return GetArguments (reader, false);
573                 }
574
575                 // Cribbed from mcs/driver.cs:LoadArgs(string)
576                 static IEnumerable<string> GetArguments (TextReader reader, bool close)
577                 {
578                         try {
579                                 StringBuilder arg = new StringBuilder ();
580
581                                 string line;
582                                 while ((line = reader.ReadLine ()) != null) {
583                                         int t = line.Length;
584
585                                         for (int i = 0; i < t; i++) {
586                                                 char c = line [i];
587                                                 
588                                                 if (c == '"' || c == '\'') {
589                                                         char end = c;
590                                                         
591                                                         for (i++; i < t; i++){
592                                                                 c = line [i];
593
594                                                                 if (c == end)
595                                                                         break;
596                                                                 arg.Append (c);
597                                                         }
598                                                 } else if (c == ' ') {
599                                                         if (arg.Length > 0) {
600                                                                 yield return arg.ToString ();
601                                                                 arg.Length = 0;
602                                                         }
603                                                 } else
604                                                         arg.Append (c);
605                                         }
606                                         if (arg.Length > 0) {
607                                                 yield return arg.ToString ();
608                                                 arg.Length = 0;
609                                         }
610                                 }
611                         }
612                         finally {
613                                 if (close)
614                                         reader.Close ();
615                         }
616                 }
617         }
618
619         public class ResponseFileSource : ArgumentSource {
620
621                 public override string[] GetNames ()
622                 {
623                         return new string[]{"@file"};
624                 }
625
626                 public override string Description {
627                         get {return "Read response file for more options.";}
628                 }
629
630                 public override bool GetArguments (string value, out IEnumerable<string> replacement)
631                 {
632                         if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) {
633                                 replacement = null;
634                                 return false;
635                         }
636                         replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1));
637                         return true;
638                 }
639         }
640
641         [Serializable]
642         public class OptionException : Exception {
643                 private string option;
644
645                 public OptionException ()
646                 {
647                 }
648
649                 public OptionException (string message, string optionName)
650                         : base (message)
651                 {
652                         this.option = optionName;
653                 }
654
655                 public OptionException (string message, string optionName, Exception innerException)
656                         : base (message, innerException)
657                 {
658                         this.option = optionName;
659                 }
660
661                 protected OptionException (SerializationInfo info, StreamingContext context)
662                         : base (info, context)
663                 {
664                         this.option = info.GetString ("OptionName");
665                 }
666
667                 public string OptionName {
668                         get {return this.option;}
669                 }
670
671                 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
672                 public override void GetObjectData (SerializationInfo info, StreamingContext context)
673                 {
674                         base.GetObjectData (info, context);
675                         info.AddValue ("OptionName", option);
676                 }
677         }
678
679         public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
680
681         public class OptionSet : KeyedCollection<string, Option>
682         {
683                 public OptionSet ()
684                         : this (delegate (string f) {return f;})
685                 {
686                 }
687
688                 public OptionSet (Converter<string, string> localizer)
689                 {
690                         this.localizer = localizer;
691                         this.roSources = new ReadOnlyCollection<ArgumentSource>(sources);
692                 }
693
694                 Converter<string, string> localizer;
695
696                 public Converter<string, string> MessageLocalizer {
697                         get {return localizer;}
698                 }
699
700                 List<ArgumentSource> sources = new List<ArgumentSource> ();
701                 ReadOnlyCollection<ArgumentSource> roSources;
702
703                 public ReadOnlyCollection<ArgumentSource> ArgumentSources {
704                         get {return roSources;}
705                 }
706
707
708                 protected override string GetKeyForItem (Option item)
709                 {
710                         if (item == null)
711                                 throw new ArgumentNullException ("option");
712                         if (item.Names != null && item.Names.Length > 0)
713                                 return item.Names [0];
714                         // This should never happen, as it's invalid for Option to be
715                         // constructed w/o any names.
716                         throw new InvalidOperationException ("Option has no names!");
717                 }
718
719                 [Obsolete ("Use KeyedCollection.this[string]")]
720                 protected Option GetOptionForName (string option)
721                 {
722                         if (option == null)
723                                 throw new ArgumentNullException ("option");
724                         try {
725                                 return base [option];
726                         }
727                         catch (KeyNotFoundException) {
728                                 return null;
729                         }
730                 }
731
732                 protected override void InsertItem (int index, Option item)
733                 {
734                         base.InsertItem (index, item);
735                         AddImpl (item);
736                 }
737
738                 protected override void RemoveItem (int index)
739                 {
740                         Option p = Items [index];
741                         base.RemoveItem (index);
742                         // KeyedCollection.RemoveItem() handles the 0th item
743                         for (int i = 1; i < p.Names.Length; ++i) {
744                                 Dictionary.Remove (p.Names [i]);
745                         }
746                 }
747
748                 protected override void SetItem (int index, Option item)
749                 {
750                         base.SetItem (index, item);
751                         AddImpl (item);
752                 }
753
754                 private void AddImpl (Option option)
755                 {
756                         if (option == null)
757                                 throw new ArgumentNullException ("option");
758                         List<string> added = new List<string> (option.Names.Length);
759                         try {
760                                 // KeyedCollection.InsertItem/SetItem handle the 0th name.
761                                 for (int i = 1; i < option.Names.Length; ++i) {
762                                         Dictionary.Add (option.Names [i], option);
763                                         added.Add (option.Names [i]);
764                                 }
765                         }
766                         catch (Exception) {
767                                 foreach (string name in added)
768                                         Dictionary.Remove (name);
769                                 throw;
770                         }
771                 }
772
773                 public OptionSet Add (string header)
774                 {
775                         if (header == null)
776                                 throw new ArgumentNullException ("header");
777                         Add (new Category (header));
778                         return this;
779                 }
780
781                 internal sealed class Category : Option {
782
783                         // Prototype starts with '=' because this is an invalid prototype
784                         // (see Option.ParsePrototype(), and thus it'll prevent Category
785                         // instances from being accidentally used as normal options.
786                         public Category (string description)
787                                 : base ("=:Category:= " + description, description)
788                         {
789                         }
790
791                         protected override void OnParseComplete (OptionContext c)
792                         {
793                                 throw new NotSupportedException ("Category.OnParseComplete should not be invoked.");
794                         }
795                 }
796
797
798                 public new OptionSet Add (Option option)
799                 {
800                         base.Add (option);
801                         return this;
802                 }
803
804                 sealed class ActionOption : Option {
805                         Action<OptionValueCollection> action;
806
807                         public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
808                                 : base (prototype, description, count)
809                         {
810                                 if (action == null)
811                                         throw new ArgumentNullException ("action");
812                                 this.action = action;
813                         }
814
815                         protected override void OnParseComplete (OptionContext c)
816                         {
817                                 action (c.OptionValues);
818                         }
819                 }
820
821                 public OptionSet Add (string prototype, Action<string> action)
822                 {
823                         return Add (prototype, null, action);
824                 }
825
826                 public OptionSet Add (string prototype, string description, Action<string> action)
827                 {
828                         if (action == null)
829                                 throw new ArgumentNullException ("action");
830                         Option p = new ActionOption (prototype, description, 1, 
831                                         delegate (OptionValueCollection v) { action (v [0]); });
832                         base.Add (p);
833                         return this;
834                 }
835
836                 public OptionSet Add (string prototype, OptionAction<string, string> action)
837                 {
838                         return Add (prototype, null, action);
839                 }
840
841                 public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
842                 {
843                         if (action == null)
844                                 throw new ArgumentNullException ("action");
845                         Option p = new ActionOption (prototype, description, 2, 
846                                         delegate (OptionValueCollection v) {action (v [0], v [1]);});
847                         base.Add (p);
848                         return this;
849                 }
850
851                 sealed class ActionOption<T> : Option {
852                         Action<T> action;
853
854                         public ActionOption (string prototype, string description, Action<T> action)
855                                 : base (prototype, description, 1)
856                         {
857                                 if (action == null)
858                                         throw new ArgumentNullException ("action");
859                                 this.action = action;
860                         }
861
862                         protected override void OnParseComplete (OptionContext c)
863                         {
864                                 action (Parse<T> (c.OptionValues [0], c));
865                         }
866                 }
867
868                 sealed class ActionOption<TKey, TValue> : Option {
869                         OptionAction<TKey, TValue> action;
870
871                         public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
872                                 : base (prototype, description, 2)
873                         {
874                                 if (action == null)
875                                         throw new ArgumentNullException ("action");
876                                 this.action = action;
877                         }
878
879                         protected override void OnParseComplete (OptionContext c)
880                         {
881                                 action (
882                                                 Parse<TKey> (c.OptionValues [0], c),
883                                                 Parse<TValue> (c.OptionValues [1], c));
884                         }
885                 }
886
887                 public OptionSet Add<T> (string prototype, Action<T> action)
888                 {
889                         return Add (prototype, null, action);
890                 }
891
892                 public OptionSet Add<T> (string prototype, string description, Action<T> action)
893                 {
894                         return Add (new ActionOption<T> (prototype, description, action));
895                 }
896
897                 public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
898                 {
899                         return Add (prototype, null, action);
900                 }
901
902                 public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
903                 {
904                         return Add (new ActionOption<TKey, TValue> (prototype, description, action));
905                 }
906
907                 public OptionSet Add (ArgumentSource source)
908                 {
909                         if (source == null)
910                                 throw new ArgumentNullException ("source");
911                         sources.Add (source);
912                         return this;
913                 }
914
915                 protected virtual OptionContext CreateOptionContext ()
916                 {
917                         return new OptionContext (this);
918                 }
919
920                 public List<string> Parse (IEnumerable<string> arguments)
921                 {
922                         if (arguments == null)
923                                 throw new ArgumentNullException ("arguments");
924                         OptionContext c = CreateOptionContext ();
925                         c.OptionIndex = -1;
926                         bool process = true;
927                         List<string> unprocessed = new List<string> ();
928                         Option def = Contains ("<>") ? this ["<>"] : null;
929                         ArgumentEnumerator ae = new ArgumentEnumerator (arguments);
930                         foreach (string argument in ae) {
931                                 ++c.OptionIndex;
932                                 if (argument == "--") {
933                                         process = false;
934                                         continue;
935                                 }
936                                 if (!process) {
937                                         Unprocessed (unprocessed, def, c, argument);
938                                         continue;
939                                 }
940                                 if (AddSource (ae, argument))
941                                         continue;
942                                 if (!Parse (argument, c))
943                                         Unprocessed (unprocessed, def, c, argument);
944                         }
945                         if (c.Option != null)
946                                 c.Option.Invoke (c);
947                         return unprocessed;
948                 }
949
950                 class ArgumentEnumerator : IEnumerable<string> {
951                         List<IEnumerator<string>> sources = new List<IEnumerator<string>> ();
952
953                         public ArgumentEnumerator (IEnumerable<string> arguments)
954                         {
955                                 sources.Add (arguments.GetEnumerator ());
956                         }
957
958                         public void Add (IEnumerable<string> arguments)
959                         {
960                                 sources.Add (arguments.GetEnumerator ());
961                         }
962
963                         public IEnumerator<string> GetEnumerator ()
964                         {
965                                 do {
966                                         IEnumerator<string> c = sources [sources.Count-1];
967                                         if (c.MoveNext ())
968                                                 yield return c.Current;
969                                         else {
970                                                 c.Dispose ();
971                                                 sources.RemoveAt (sources.Count-1);
972                                         }
973                                 } while (sources.Count > 0);
974                         }
975
976                         IEnumerator IEnumerable.GetEnumerator ()
977                         {
978                                 return GetEnumerator ();
979                         }
980                 }
981
982                 bool AddSource (ArgumentEnumerator ae, string argument)
983                 {
984                         foreach (ArgumentSource source in sources) {
985                                 IEnumerable<string> replacement;
986                                 if (!source.GetArguments (argument, out replacement))
987                                         continue;
988                                 ae.Add (replacement);
989                                 return true;
990                         }
991                         return false;
992                 }
993
994                 private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
995                 {
996                         if (def == null) {
997                                 extra.Add (argument);
998                                 return false;
999                         }
1000                         c.OptionValues.Add (argument);
1001                         c.Option = def;
1002                         c.Option.Invoke (c);
1003                         return false;
1004                 }
1005
1006                 private readonly Regex ValueOption = new Regex (
1007                         @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
1008
1009                 protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
1010                 {
1011                         if (argument == null)
1012                                 throw new ArgumentNullException ("argument");
1013
1014                         flag = name = sep = value = null;
1015                         Match m = ValueOption.Match (argument);
1016                         if (!m.Success) {
1017                                 return false;
1018                         }
1019                         flag  = m.Groups ["flag"].Value;
1020                         name  = m.Groups ["name"].Value;
1021                         if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
1022                                 sep   = m.Groups ["sep"].Value;
1023                                 value = m.Groups ["value"].Value;
1024                         }
1025                         return true;
1026                 }
1027
1028                 protected virtual bool Parse (string argument, OptionContext c)
1029                 {
1030                         if (c.Option != null) {
1031                                 ParseValue (argument, c);
1032                                 return true;
1033                         }
1034
1035                         string f, n, s, v;
1036                         if (!GetOptionParts (argument, out f, out n, out s, out v))
1037                                 return false;
1038
1039                         Option p;
1040                         if (Contains (n)) {
1041                                 p = this [n];
1042                                 c.OptionName = f + n;
1043                                 c.Option     = p;
1044                                 switch (p.OptionValueType) {
1045                                         case OptionValueType.None:
1046                                                 c.OptionValues.Add (n);
1047                                                 c.Option.Invoke (c);
1048                                                 break;
1049                                         case OptionValueType.Optional:
1050                                         case OptionValueType.Required: 
1051                                                 ParseValue (v, c);
1052                                                 break;
1053                                 }
1054                                 return true;
1055                         }
1056                         // no match; is it a bool option?
1057                         if (ParseBool (argument, n, c))
1058                                 return true;
1059                         // is it a bundled option?
1060                         if (ParseBundledValue (f, string.Concat (n + s + v), c))
1061                                 return true;
1062
1063                         return false;
1064                 }
1065
1066                 private void ParseValue (string option, OptionContext c)
1067                 {
1068                         if (option != null)
1069                                 foreach (string o in c.Option.ValueSeparators != null 
1070                                                 ? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None)
1071                                                 : new string[]{option}) {
1072                                         c.OptionValues.Add (o);
1073                                 }
1074                         if (c.OptionValues.Count == c.Option.MaxValueCount || 
1075                                         c.Option.OptionValueType == OptionValueType.Optional)
1076                                 c.Option.Invoke (c);
1077                         else if (c.OptionValues.Count > c.Option.MaxValueCount) {
1078                                 throw new OptionException (localizer (string.Format (
1079                                                                 "Error: Found {0} option values when expecting {1}.", 
1080                                                                 c.OptionValues.Count, c.Option.MaxValueCount)),
1081                                                 c.OptionName);
1082                         }
1083                 }
1084
1085                 private bool ParseBool (string option, string n, OptionContext c)
1086                 {
1087                         Option p;
1088                         string rn;
1089                         if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
1090                                         Contains ((rn = n.Substring (0, n.Length-1)))) {
1091                                 p = this [rn];
1092                                 string v = n [n.Length-1] == '+' ? option : null;
1093                                 c.OptionName  = option;
1094                                 c.Option      = p;
1095                                 c.OptionValues.Add (v);
1096                                 p.Invoke (c);
1097                                 return true;
1098                         }
1099                         return false;
1100                 }
1101
1102                 private bool ParseBundledValue (string f, string n, OptionContext c)
1103                 {
1104                         if (f != "-")
1105                                 return false;
1106                         for (int i = 0; i < n.Length; ++i) {
1107                                 Option p;
1108                                 string opt = f + n [i].ToString ();
1109                                 string rn = n [i].ToString ();
1110                                 if (!Contains (rn)) {
1111                                         if (i == 0)
1112                                                 return false;
1113                                         throw new OptionException (string.Format (localizer (
1114                                                                         "Cannot bundle unregistered option '{0}'."), opt), opt);
1115                                 }
1116                                 p = this [rn];
1117                                 switch (p.OptionValueType) {
1118                                         case OptionValueType.None:
1119                                                 Invoke (c, opt, n, p);
1120                                                 break;
1121                                         case OptionValueType.Optional:
1122                                         case OptionValueType.Required: {
1123                                                 string v     = n.Substring (i+1);
1124                                                 c.Option     = p;
1125                                                 c.OptionName = opt;
1126                                                 ParseValue (v.Length != 0 ? v : null, c);
1127                                                 return true;
1128                                         }
1129                                         default:
1130                                                 throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
1131                                 }
1132                         }
1133                         return true;
1134                 }
1135
1136                 private static void Invoke (OptionContext c, string name, string value, Option option)
1137                 {
1138                         c.OptionName  = name;
1139                         c.Option      = option;
1140                         c.OptionValues.Add (value);
1141                         option.Invoke (c);
1142                 }
1143
1144                 private const int OptionWidth = 29;
1145                 private const int Description_FirstWidth  = 80 - OptionWidth;
1146                 private const int Description_RemWidth    = 80 - OptionWidth - 2;
1147
1148                 public void WriteOptionDescriptions (TextWriter o)
1149                 {
1150                         foreach (Option p in this) {
1151                                 int written = 0;
1152
1153                                 Category c = p as Category;
1154                                 if (c != null) {
1155                                         WriteDescription (o, p.Description, "", 80, 80);
1156                                         continue;
1157                                 }
1158
1159                                 if (!WriteOptionPrototype (o, p, ref written))
1160                                         continue;
1161
1162                                 if (written < OptionWidth)
1163                                         o.Write (new string (' ', OptionWidth - written));
1164                                 else {
1165                                         o.WriteLine ();
1166                                         o.Write (new string (' ', OptionWidth));
1167                                 }
1168
1169                                 WriteDescription (o, p.Description, new string (' ', OptionWidth+2),
1170                                                 Description_FirstWidth, Description_RemWidth);
1171                         }
1172
1173                         foreach (ArgumentSource s in sources) {
1174                                 string[] names = s.GetNames ();
1175                                 if (names == null || names.Length == 0)
1176                                         continue;
1177
1178                                 int written = 0;
1179
1180                                 Write (o, ref written, "  ");
1181                                 Write (o, ref written, names [0]);
1182                                 for (int i = 1; i < names.Length; ++i) {
1183                                         Write (o, ref written, ", ");
1184                                         Write (o, ref written, names [i]);
1185                                 }
1186
1187                                 if (written < OptionWidth)
1188                                         o.Write (new string (' ', OptionWidth - written));
1189                                 else {
1190                                         o.WriteLine ();
1191                                         o.Write (new string (' ', OptionWidth));
1192                                 }
1193
1194                                 WriteDescription (o, s.Description, new string (' ', OptionWidth+2),
1195                                                 Description_FirstWidth, Description_RemWidth);
1196                         }
1197                 }
1198
1199                 void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth)
1200                 {
1201                         bool indent = false;
1202                         foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) {
1203                                 if (indent)
1204                                         o.Write (prefix);
1205                                 o.WriteLine (line);
1206                                 indent = true;
1207                         }
1208                 }
1209
1210                 bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
1211                 {
1212                         string[] names = p.Names;
1213
1214                         int i = GetNextOptionIndex (names, 0);
1215                         if (i == names.Length)
1216                                 return false;
1217
1218                         if (names [i].Length == 1) {
1219                                 Write (o, ref written, "  -");
1220                                 Write (o, ref written, names [0]);
1221                         }
1222                         else {
1223                                 Write (o, ref written, "      --");
1224                                 Write (o, ref written, names [0]);
1225                         }
1226
1227                         for ( i = GetNextOptionIndex (names, i+1); 
1228                                         i < names.Length; i = GetNextOptionIndex (names, i+1)) {
1229                                 Write (o, ref written, ", ");
1230                                 Write (o, ref written, names [i].Length == 1 ? "-" : "--");
1231                                 Write (o, ref written, names [i]);
1232                         }
1233
1234                         if (p.OptionValueType == OptionValueType.Optional ||
1235                                         p.OptionValueType == OptionValueType.Required) {
1236                                 if (p.OptionValueType == OptionValueType.Optional) {
1237                                         Write (o, ref written, localizer ("["));
1238                                 }
1239                                 Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
1240                                 string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 
1241                                         ? p.ValueSeparators [0]
1242                                         : " ";
1243                                 for (int c = 1; c < p.MaxValueCount; ++c) {
1244                                         Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
1245                                 }
1246                                 if (p.OptionValueType == OptionValueType.Optional) {
1247                                         Write (o, ref written, localizer ("]"));
1248                                 }
1249                         }
1250                         return true;
1251                 }
1252
1253                 static int GetNextOptionIndex (string[] names, int i)
1254                 {
1255                         while (i < names.Length && names [i] == "<>") {
1256                                 ++i;
1257                         }
1258                         return i;
1259                 }
1260
1261                 static void Write (TextWriter o, ref int n, string s)
1262                 {
1263                         n += s.Length;
1264                         o.Write (s);
1265                 }
1266
1267                 private static string GetArgumentName (int index, int maxIndex, string description)
1268                 {
1269                         if (description == null)
1270                                 return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1271                         string[] nameStart;
1272                         if (maxIndex == 1)
1273                                 nameStart = new string[]{"{0:", "{"};
1274                         else
1275                                 nameStart = new string[]{"{" + index + ":"};
1276                         for (int i = 0; i < nameStart.Length; ++i) {
1277                                 int start, j = 0;
1278                                 do {
1279                                         start = description.IndexOf (nameStart [i], j);
1280                                 } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
1281                                 if (start == -1)
1282                                         continue;
1283                                 int end = description.IndexOf ("}", start);
1284                                 if (end == -1)
1285                                         continue;
1286                                 return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
1287                         }
1288                         return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1289                 }
1290
1291                 private static string GetDescription (string description)
1292                 {
1293                         if (description == null)
1294                                 return string.Empty;
1295                         StringBuilder sb = new StringBuilder (description.Length);
1296                         int start = -1;
1297                         for (int i = 0; i < description.Length; ++i) {
1298                                 switch (description [i]) {
1299                                         case '{':
1300                                                 if (i == start) {
1301                                                         sb.Append ('{');
1302                                                         start = -1;
1303                                                 }
1304                                                 else if (start < 0)
1305                                                         start = i + 1;
1306                                                 break;
1307                                         case '}':
1308                                                 if (start < 0) {
1309                                                         if ((i+1) == description.Length || description [i+1] != '}')
1310                                                                 throw new InvalidOperationException ("Invalid option description: " + description);
1311                                                         ++i;
1312                                                         sb.Append ("}");
1313                                                 }
1314                                                 else {
1315                                                         sb.Append (description.Substring (start, i - start));
1316                                                         start = -1;
1317                                                 }
1318                                                 break;
1319                                         case ':':
1320                                                 if (start < 0)
1321                                                         goto default;
1322                                                 start = i + 1;
1323                                                 break;
1324                                         default:
1325                                                 if (start < 0)
1326                                                         sb.Append (description [i]);
1327                                                 break;
1328                                 }
1329                         }
1330                         return sb.ToString ();
1331                 }
1332
1333                 private static IEnumerable<string> GetLines (string description, int firstWidth, int remWidth)
1334                 {
1335                         return StringCoda.WrappedLines (description, firstWidth, remWidth);
1336                 }
1337         }
1338 }
1339