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