| 1 |
/* |
| 2 |
* Copyright (C)2005-2022 Haxe Foundation |
| 3 |
* |
| 4 |
* Permission is hereby granted, free of charge, to any person obtaining a |
| 5 |
* copy of this software and associated documentation files (the "Software"), |
| 6 |
* to deal in the Software without restriction, including without limitation |
| 7 |
* the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| 8 |
* and/or sell copies of the Software, and to permit persons to whom the |
| 9 |
* Software is furnished to do so, subject to the following conditions: |
| 10 |
* |
| 11 |
* The above copyright notice and this permission notice shall be included in |
| 12 |
* all copies or substantial portions of the Software. |
| 13 |
* |
| 14 |
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 15 |
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 16 |
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 17 |
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 18 |
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 19 |
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
| 20 |
* DEALINGS IN THE SOFTWARE. |
| 21 |
*/ |
| 22 |
|
| 23 |
type argtype { |
| 24 |
Void : void -> void; |
| 25 |
String : string -> void; |
| 26 |
Int : int -> void; |
| 27 |
} |
| 28 |
|
| 29 |
exception Invalid; |
| 30 |
|
| 31 |
function help(head,decl) { |
| 32 |
print head; |
| 33 |
print "\n Options :\n"; |
| 34 |
List.iter (function((name,_,help)) { |
| 35 |
printf " %s %s\n" (name,help); |
| 36 |
}) decl; |
| 37 |
Sys.exit(1) |
| 38 |
} |
| 39 |
|
| 40 |
function parse_args(args,head,decl,def) { |
| 41 |
var i = &0; |
| 42 |
var l = Array.length args; |
| 43 |
var h = Hashtbl.create(); |
| 44 |
var hdecl = Void (function() { help head decl }); |
| 45 |
Hashtbl.add h "-help" hdecl; |
| 46 |
Hashtbl.add h "--help" hdecl; |
| 47 |
List.iter (function((name,decl,_)) { |
| 48 |
Hashtbl.add h name decl; |
| 49 |
}) decl; |
| 50 |
try { |
| 51 |
while *i < l { |
| 52 |
var arg = args.[*i]; |
| 53 |
i := *i + 1; |
| 54 |
var d = try { Hashtbl.find h arg; } catch { Not_found -> Void (function() { def arg }) }; |
| 55 |
match d { |
| 56 |
| Void f -> |
| 57 |
f() |
| 58 |
| String f -> |
| 59 |
if *i == l then throw Invalid; |
| 60 |
var param = args.[*i]; |
| 61 |
i := *i + 1; |
| 62 |
f param |
| 63 |
| Int f -> |
| 64 |
if *i == l then throw Invalid; |
| 65 |
var param = args.[*i]; |
| 66 |
i := *i + 1; |
| 67 |
var pval = try { int param } catch { _ -> throw Invalid }; |
| 68 |
f pval |
| 69 |
} |
| 70 |
} |
| 71 |
} catch { |
| 72 |
Invalid -> |
| 73 |
var arg = args.[*i - 1]; |
| 74 |
print "Invalid argument : "; |
| 75 |
print arg; |
| 76 |
print "\n"; |
| 77 |
help head decl |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
function parse(head,decl,def) { |
| 82 |
parse_args(Sys.args(),head,decl,def); |
| 83 |
} |