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