diff --git a/mshell/Program.cs b/mshell/Program.cs index 395af66..f8edc2f 100755 --- a/mshell/Program.cs +++ b/mshell/Program.cs @@ -15,18 +15,23 @@ static int Main(string[] args) bool printLex = false; string? input = null; + List positionalArgs = new List(); while (i < args.Length) { - if (args[i] == "--lex") + var arg = args[i]; + i++; + if (arg == "--lex") { printLex = true; } + else if (input is not null) + { + positionalArgs.Add(arg); + } else { - input = File.ReadAllText(args[i]); + input = File.ReadAllText(arg); } - - i++; } input ??= Console.In.ReadToEnd(); @@ -47,7 +52,7 @@ static int Main(string[] args) return 0; } - Evaluator e = new(false); + Evaluator e = new(false, positionalArgs); EvalResult result = e.Evaluate(tokens, new Stack(), new ExecuteContext()); return result.Success ? 0 : 1; @@ -118,11 +123,25 @@ private TokenNew ScanToken() return MakeToken(TokenType.PIPE); case '?': return MakeToken(TokenType.QUESTION); + case '$': + return char.IsDigit(Peek()) ? ParsePositional() : ParseLiteralOrNumber(); default: return ParseLiteralOrNumber(); } } + private TokenNew ParsePositional() + { + while (true) + { + if (AtEnd()) break; + var c = Advance(); + if (!char.IsDigit(c)) break; + } + + return MakeToken(TokenType.POSITIONAL); + } + private TokenNew ParseString() { // When this is called, we've already consumed a single double quote. @@ -233,6 +252,7 @@ private void EatWhitespace() public class Evaluator { + private readonly List _positionalArgs; private readonly Action> _push; private int _loopDepth = 0; @@ -240,8 +260,9 @@ public class Evaluator // private Stack> _stack = new(); - public Evaluator(bool debug) + public Evaluator(bool debug, List positionalArgs) { + _positionalArgs = positionalArgs; _push = debug ? PushWithDebug : PushNoDebug; // _tokens = tokens; // Stack> stack = new(); @@ -903,6 +924,23 @@ public EvalResult Evaluate(List tokens, Stack stack, Exe } } } + else if (t.TokenType == TokenType.POSITIONAL) + { + int positionalNum = int.Parse(t.RawText[1..]); + if (positionalNum < 1) + { + return FailWithMessage($"Found positional argument less than 1 ({t.RawText}). Positional arguments start at 1.\n"); + } + + if (positionalNum > _positionalArgs.Count) + { + return FailWithMessage($"Found positional argument greater than total supplied ({t.RawText}, {_positionalArgs.Count} supplied).\n"); + } + + MShellString s = new MShellString(_positionalArgs[positionalNum - 1]); + _push(s, stack); + index++; + } else { return FailWithMessage($"Token type '{t.TokenType}' (Raw Token: '{t.RawText}') not implemented yet.\n"); @@ -1179,7 +1217,8 @@ public enum TokenType PLUS, PIPE, INTERPRET, - QUESTION + QUESTION, + POSITIONAL } public class TokenNew diff --git a/mshell/positional.msh b/mshell/positional.msh new file mode 100644 index 0000000..05e41d5 --- /dev/null +++ b/mshell/positional.msh @@ -0,0 +1,2 @@ +[echo "Number 1: " $1 +]; +[echo "Number 2: " $2 +];