Exemple #1
0
            public SkryptObject Explode(SkryptEngine engine, SkryptObject self, SkryptObject[] input)
            {
                var delimiter  = TypeConverter.ToString(input, 0, engine);
                var selfString = ((String)self).Value;

                var exploded = !string.IsNullOrEmpty(delimiter) ?
                               selfString.Split(new string[] { delimiter }, Sys.StringSplitOptions.None) :
                               new string[] { selfString };

                var array = engine.Create <Array>();

                for (int i = 0; i < exploded.Length; i++)
                {
                    array.List.Add(engine.Create <String>(exploded[i]));
                }

                return(array);
            }
            public static SkryptObject Small(SkryptEngine engine, SkryptObject self, SkryptObject[] values)
            {
                var a = (Array)TypeConverter.ToArray(values, 0).Clone(); // Copy array so we don't affect the original one by sorting it
                var k = TypeConverter.ToNumeric(values, 1);

                a.List.Sort((x, y) => {
                    if ((Numeric)x > (Numeric)y)
                    {
                        return(1);
                    }
                    else
                    {
                        return(-1);
                    }
                });

                return(engine.Create <Numeric>(a.List[a.List.Count - (int)k - 1]));
            }
        public static SkryptObject ToJson(SkryptEngine engine, SkryptObject self, Arguments arguments)
        {
            var value          = arguments[0];
            var indented       = arguments.Length > 1 ? arguments.GetAs <BooleanInstance>(1): false;
            var writeFunctions = arguments.Length > 2 ? arguments.GetAs <BooleanInstance>(2) : false;

            var jsonString = JsonConvert.SerializeObject(value, indented ? Formatting.Indented : Formatting.None, new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                Converters            = new JsonConverter[] {
                    new SkryptNumberJsonConverter(),
                    new SkryptStringJsonConverter(),
                    new SkryptBooleanJsonConverter(),
                    new SkryptArrayJsonConverter(),
                    new SkryptObjectJsonConverter(writeFunctions)
                }
            });

            return(engine.CreateString(jsonString));
        }
            public static SkryptObject CountEmpty(SkryptEngine engine, SkryptObject self, SkryptObject[] values)
            {
                var a     = TypeConverter.ToArray(values, 0);
                var empty = 0;

                for (int i = 0; i < a.List.Count; i++)
                {
                    if (a.List[i] == null || a.List[i] == (String)"")
                    {
                        empty++;
                    }
                    else
                    {
                        empty--;
                    }
                }

                return(engine.Create <Numeric>(empty));
            }
        /// <summary>
        ///     Parses an include statement.
        /// </summary>
        public ParseResult ParseInclude(List <Token> tokens)
        {
            var skip = _engine.ExpectType(TokenTypes.StringLiteral, tokens);

            if (string.IsNullOrEmpty(_engine.Root))
            {
                _engine.ThrowError("Engine path invalid!", tokens[1]);
            }

            var desiredFile = tokens[1].Value.EndsWith(".skt") ? tokens[1].Value : tokens[1].Value + ".skt";
            var path        = Path.GetFullPath(Path.Combine(_engine.Root, desiredFile));
            var fileName    = SkryptEngine.MakeRelativePath(_engine.Root, path);
            var fileStream  = File.Open(path, FileMode.Open);

            string includedCode;

            using (var sr = new StreamReader(fileStream)) {
                includedCode = sr.ReadToEnd();
            }

            _engine.Files[fileName] = includedCode;

            var oldParsingFile = _engine.CurrentParsingFile;

            _engine.CurrentParsingFile = path;

            var includeTokens = _engine.Tokenizer.Tokenize(includedCode);

            _engine.TokenProcessor.ProcessTokens(includeTokens);

            var programNode = _engine.GeneralParser.Parse(includeTokens);
            var node        = new IncludeNode {
                Nodes = programNode.Nodes,
                Path  = fileName
            };

            _engine.CurrentParsingFile = oldParsingFile;

            return(new ParseResult {
                Node = node, Delta = 3
            });
        }
Exemple #6
0
            public SkryptObject Map(SkryptEngine engine, SkryptObject self, SkryptObject[] values)
            {
                var m = TypeConverter.ToMethod(values, 0);

                var newArray = engine.Create <Array>(((Array)self).List);

                if (m.GetType() == typeof(SkryptMethod) && m.Parameters.Count != 1)
                {
                    engine.ThrowError("Input function must have 1 parameter!");
                }

                var scope = SkryptMethod.GetPopulatedScope(m, new[] { new Null() });

                scope.ParentScope = engine.CurrentScope;
                var name = scope.Variables.Keys.First();

                for (int i = 0; i < newArray.List.Count; i++)
                {
                    var x = newArray.List[i];

                    scope.Variables[name].Value = x;

                    var r = m.Execute(engine, self, new[] { x }, scope);

                    ((Array)self).List[i] = scope.Variables[name].Value;
                }

                var iterator = new Dictionary <string, SkryptObject>(((Array)self).Table);

                foreach (var p in iterator)
                {
                    var x = p.Value;

                    scope.Variables[name].Value = x;

                    var r = m.Execute(engine, self, new[] { x }, scope);

                    newArray.Table[p.Key] = scope.Variables[name].Value;
                }

                return(newArray);
            }
        public override ScopeContext Execute(SkryptEngine engine, SkryptObject self, SkryptObject[] parameters, ScopeContext scope)
        {
            var returnValue = Method(self, parameters);

            if (typeof(SkryptType).IsAssignableFrom(returnValue.GetType()))
            {
                returnValue.GetPropertiesFrom(engine.Executor.GetType(((SkryptType)returnValue).TypeName, scope));
            }

            var newScope = new ScopeContext {
                ParentScope = scope,
                Properties  = scope.Properties
            };

            newScope.ReturnObject        = returnValue;
            newScope.ReturnObject.Engine = engine;
            newScope.Variables           = new Dictionary <string, Variable>(scope.Variables);

            return(newScope);
        }
Exemple #8
0
            public static SkryptObject AESEncrypt(SkryptEngine engine, SkryptObject self, SkryptObject[] values)
            {
                var toEncrypt = TypeConverter.ToString(values, 0, engine);
                var password  = TypeConverter.ToString(values, 1, engine);

                var bytesToBeEncrypted = Sys.Text.Encoding.UTF8.GetBytes(toEncrypt);
                var passwordBytes      = Sys.Text.Encoding.UTF8.GetBytes(password);

                // Hash the password with SHA256
                passwordBytes = Sys.Security.Cryptography.SHA256.Create().ComputeHash(passwordBytes);

                byte[] encryptedBytes = null;

                // Set your salt here, change it to meet your flavor:
                // The salt bytes must be at least 8 bytes.
                byte[] saltBytes = new byte[] { 2, 64, 56, 76, 12, 10, 23, 5 };

                using (MemoryStream ms = new MemoryStream()) {
                    using (RijndaelManaged AES = new RijndaelManaged()) {
                        AES.KeySize   = 256;
                        AES.BlockSize = 128;

                        var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                        AES.Key = key.GetBytes(AES.KeySize / 8);
                        AES.IV  = key.GetBytes(AES.BlockSize / 8);

                        AES.Mode = CipherMode.CBC;

                        using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) {
                            cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                            cs.Close();
                        }
                        encryptedBytes = ms.ToArray();
                    }
                }

                var result = Convert.ToBase64String(encryptedBytes);

                return(engine.Create <String>(result));
            }
Exemple #9
0
            public SkryptObject Remove(SkryptEngine engine, SkryptObject self, SkryptObject[] values)
            {
                var i = TypeConverter.ToAny(values, 0);

                if (i.GetType() == typeof(Numeric))
                {
                    if ((int)(Numeric)i > 0 && (int)(Numeric)i < ((Array)self).List.Count - 1)
                    {
                        ((Array)self).List.RemoveAt((int)(Numeric)i);
                    }
                }
                else if (i.GetType() == typeof(String))
                {
                    ((Array)self).Table.Remove((String)i);
                }
                else
                {
                    engine.ThrowError("Array index can only be string or numeric.");
                }

                return((Array)self);
            }
        public static SkryptObject ConvertToSkryptObject(SkryptEngine engine, object value)
        {
            if (value == null)
            {
                return(null);
            }

            if (IsNumber(value))
            {
                return(ToNumberInstance(engine, Convert.ToDouble(value)));
            }
            else if (value.GetType() == typeof(bool))
            {
                return(ToBooleanInstance(engine, Convert.ToBoolean(value)));
            }
            else if (value.GetType() == typeof(string))
            {
                return(ToStringInstance(engine, Convert.ToString(value)));
            }

            return(null);
        }
Exemple #11
0
        public SkryptObject Run(SkryptEngine engine, SkryptObject self, Arguments arguments)
        {
            SkryptObject result = null;

            var isValid = Function.HasValidArguments(arguments);

            if (isValid)
            {
                var args = Function.ConvertArguments(arguments);
                var res  = Function.del.DynamicInvoke(args);

                if (res != null)
                {
                    if (engine.ImportTypeMappers.ContainsKey(res.GetType()))
                    {
                        result = engine.ImportTypeMappers[res.GetType()](engine, res);
                    }
                    else
                    {
                        throw new SkryptException($"No type mapper found for {res.GetType().FullName}");
                    }
                }
            }

            if (!isValid)
            {
                var argString = "";

                foreach (var arg in arguments.Values)
                {
                    argString += arg.GetType().Name + " ";
                }

                throw new ArgumentException($"No method found for arguments {argString}");
            }

            return(result);
        }
Exemple #12
0
        public MainWindow()
        {
            InitializeComponent();

            _engine = new SkryptEngine();

            //_outputter = new Output.TextBoxOutputter(Terminal);
            //Console.SetOut(_outputter);

            var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                    @"..\..\SkryptHighlighting.xml");

            using (XmlTextReader reader = new XmlTextReader(new StreamReader(path))) {
                textEditor.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
            }

            try {
                _documentPath   = Serializing.ReadFromBinaryFile <string>(Serializing.AssemblyDirectory + "/lastDocument.txt");
                textEditor.Text = File.ReadAllText(_documentPath);
            } catch {
                _documentPath = string.Empty;
            }

            RoutedCommand newCmd = new RoutedCommand();

            newCmd.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control));
            CommandBindings.Add(new CommandBinding(newCmd, OnSave));

            newCmd = new RoutedCommand();
            newCmd.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Control));
            CommandBindings.Add(new CommandBinding(newCmd, OnNew));

            newCmd = new RoutedCommand();
            newCmd.InputGestures.Add(new KeyGesture(Key.R, ModifierKeys.Control));
            CommandBindings.Add(new CommandBinding(newCmd, OnRun));
        }
Exemple #13
0
                public static SkryptObject Request(SkryptEngine engine, SkryptObject self, SkryptObject[] values)
                {
                    var address = TypeConverter.ToString(values, 0, engine);

                    var request = (HttpWebRequest)WebRequest.Create(address);

                    request.Credentials = CredentialCache.DefaultCredentials;
                    request.ContentType = "text/plain";
                    request.Timeout     = Timeout.Infinite;
                    request.Method      = "GET";
                    request.Accept      = "text/plain";
                    request.KeepAlive   = false;

                    HttpWebResponse response = null;

                    try {
                        response = (HttpWebResponse)request.GetResponse();
                    } catch (WebException e) {
                        return(engine.Create <String>(e.Status.ToString()));
                    }

                    // Get the stream containing content returned by the server.
                    var dataStream = response.GetResponseStream();
                    // Open the stream using a StreamReader for easy access.
                    var reader = new StreamReader(dataStream);
                    // Read the content.
                    string responseFromServer = reader.ReadToEnd();

                    // Display the content.
                    Console.WriteLine(responseFromServer);
                    // Clean up the streams and the response.
                    reader.Close();
                    response.Close();

                    return(engine.Create <String>(responseFromServer));
                }
Exemple #14
0
 public ExpressionInterpreter(SkryptEngine engine)
 {
     _engine = engine;
 }
 public BasicStruct(SkryptEngine engine) : base(engine)
 {
     CreateProperty("Property", null);
 }
Exemple #16
0
 public ImageInstance(SkryptEngine engine) : base(engine)
 {
 }
Exemple #17
0
 public ImageType(SkryptEngine engine) : base(engine)
 {
     Template = engine.TemplateMaker.CreateTemplate(typeof(ImageInstance));
 }
Exemple #18
0
 public ColorInstance(SkryptEngine engine, Color col) : base(engine)
 {
     color = col;
 }
Exemple #19
0
            public static SkryptObject Sort(SkryptEngine engine, SkryptObject self, SkryptObject[] values)
            {
                var a = TypeConverter.ToArray(values, 0);

                return(a.Sort(engine, a, null));
            }
Exemple #20
0
 public virtual SkryptObject Execute(SkryptEngine engine, SkryptObject[] parameters, ScopeContext scope)
 {
     return(null);
 }
Exemple #21
0
 public ImproModule(SkryptEngine engine) : base(engine)
 {
 }
Exemple #22
0
 public StatementParser(SkryptEngine e)
 {
     engine = e;
 }
Exemple #23
0
 public ClassParser(SkryptEngine e)
 {
     _engine = e;
 }
Exemple #24
0
 public CLRFunction(SkryptEngine engine, Delegate del)
 {
     Function = CLRTypeConverter.CreateCLRFunction(engine, del);
 }
        public static Node OptimiseExpressionNode(Node node, SkryptEngine engine)
        {
            if (!node.Nodes.Any())
            {
                return(node);
            }

            var isBinaryExpression = node.Nodes.Count == 2;
            var onlyHasLiterals    = true;
            var token   = node.Token;
            var newNode = node.Copy();

            for (int i = 0; i < node.Nodes.Count; i++)
            {
                newNode.Nodes[i] = OptimiseExpressionNode(node.Nodes[i], engine);
            }

            foreach (var n in newNode.Nodes)
            {
                if ((n.Type & TokenTypes.Literal) == 0)
                {
                    onlyHasLiterals = false;
                    break;
                }
            }

            if (onlyHasLiterals)
            {
                var retVal = engine.Executor.ExecuteExpression(newNode, engine.GlobalScope);

                if (retVal.GetType() == typeof(Skrypt.Library.Native.System.Numeric))
                {
                    newNode = new NumericNode {
                        Value = (Skrypt.Library.Native.System.Numeric)retVal,
                        Token = node.Token
                    };
                }
                else if (retVal.GetType() == typeof(Skrypt.Library.Native.System.String))
                {
                    newNode = new StringNode {
                        Value = (Skrypt.Library.Native.System.String)retVal,
                        Token = node.Token
                    };
                }
                else if (retVal.GetType() == typeof(Skrypt.Library.Native.System.Boolean))
                {
                    newNode = new BooleanNode {
                        Value = (Skrypt.Library.Native.System.Boolean)retVal,
                        Token = node.Token
                    };
                }
                //else if (retVal.GetType() == typeof(Skrypt.Library.Native.System.Array)) {
                //    newNode = new ArrayNode {
                //        Value = (Skrypt.Library.Native.System.Array)retVal,
                //        Token = node.Token
                //    };
                //}
            }

            return(newNode);
        }
Exemple #26
0
 public ColorType(SkryptEngine engine) : base(engine)
 {
     Template = engine.TemplateMaker.CreateTemplate(typeof(ColorInstance));
 }
Exemple #27
0
 public ExpressionParser(SkryptEngine e)
 {
     _engine = e;
 }
Exemple #28
0
 public ColorInstance(SkryptEngine engine) : base(engine)
 {
 }
Exemple #29
0
 public override SkryptObject Execute(SkryptEngine engine, SkryptObject[] parameters, ScopeContext scope)
 {
     return(method(parameters));
 }
Exemple #30
0
 public SkryptObject ToString(SkryptEngine engine, SkryptObject self, SkryptObject[] input)
 {
     return(engine.Create <String>(((Numeric)self).Value.ToString(TypeConverter.ToString(input, 0, engine))));
 }