Example #1
0
        private static void CreateMainWindow()
        {
            var options = ObjectLiteral.Create <electron.Electron.BrowserWindowConstructorOptions>();

            options.width  = 600;
            options.height = 800;
            options.icon   = node.path.join(node.__dirname, "assets/app-icon/png/32.png");
            options.title  = GetAppNameWithVersion(true);
            options.show   = false;

            // Create the browser window.
            Win = new electron.Electron.BrowserWindow(options);
            SetContextMenu(Win);

            App.SetMainMenu();

            App.LoadWindow(Win, "forms/MainForm.html");

            Win.on(lit.closed, () =>
            {
                // Dereference the window object, usually you would store windows
                // in an array if your app supports multi windows, this is the time
                // when you should delete the corresponding element.
                Win = null;
            });

            Win.on(lit.minimize, () =>
            {
                Win.setSkipTaskbar(true);
            });
        }
Example #2
0
        public static void Main()
        {
            // Initialize settings (based on the d.ts, PromptSettings is a plain object literal):
            var promptSettings = ObjectLiteral.Create <SettingsOrPromptSettings>();

            // Set Settings type fields (Item1 has type SweetAlert.Settings):
            promptSettings.Type1.title = "SweetAlert demo";

            // Set PromtModalSettings fields (Item2 has type SweetAlert.PromtModalSettings):
            promptSettings.Type2.type             = sweetalert.Literals.input;
            promptSettings.Type2.text             = "Please enter some text or press Reject:";
            promptSettings.Type2.showCancelButton = true;
            promptSettings.Type2.cancelButtonText = "Reject";

            // In JavaScript the call would look like: swal(promptSettings, ...);
            // Since swal is an object, the same call should be done using "Self" method:

            // Show prompt and process the input:
            swal.Self(promptSettings, result =>
            {
                setTimeout(args =>
                {
                    // Show another prompt, to show the inputted text:
                    swal.Self($"Entered text: '{result}'.");
                }, 200);

                return(null);
            });
        }
Example #3
0
 private ObjectLiteral CreateObject(string name1, object value1, string name2, object value2)
 {
     return
         (ObjectLiteral.Create(new List <Binding> {
         new Binding(CreateString(name1), value1, location: default(LineInfo)), new Binding(CreateString(name2), value2, location: default(LineInfo))
     }, default(LineInfo), AbsolutePath.Invalid));
 }
Example #4
0
        void InitRange()
        {
            // ReSharper disable once UnusedVariable
            dynamic me = this;

            dynamic root = _root;

            Window.SetTimeout(() =>
            {
                if (_wrapper != null)
                {
                    return;
                }

                dynamic options  = ObjectLiteral.Create <object>();
                options.min      = Min;
                options.max      = Max;
                options.step     = Step;
                options.start    = Value;
                options.onChange = Script.Write <Function>("function(value){  me.OnUIValueChanged(value);   };");


                _wrapper = root.range(options);
            }, 1);
        }
Example #5
0
            public void TestClass()
            {
                var c = ObjectLiteral.Create <Config3>();

                c.id = 1;
                Assert.AreEqual(1, c.id);
                Assert.NotNull(c.GetHashCode());

                var c2 = ObjectLiteral.Create <Config4>();

                c2.id   = 2;
                c2.Name = "Nancy";
                Assert.AreEqual(2, c2.id);
                Assert.AreEqual("Nancy", c2.Name);
                Assert.NotNull(c2.GetHashCode());

                var c21 = ObjectLiteral.Create <Config4>();

                c21.id   = 2;
                c21.Name = "Nancy";
                Assert.False(c21 == c2);
                Assert.False(c21.Equals(c2));
                Assert.NotNull(c21.GetHashCode());

                c21.id = 21;
                Assert.False(c21 == c2);
                Assert.False(c21.Equals(c2));

                Config3 c3 = ObjectLiteral.Create <Config4>();

                c3.id = 3;
                Assert.AreEqual(3, c3.id);
                Assert.NotNull(c.GetHashCode());
            }
Example #6
0
        private static electron.Electron.BrowserWindow CreateOptionsWindow()
        {
            var options = ObjectLiteral.Create <electron.Electron.BrowserWindowConstructorOptions>();

            options.width       = 440;
            options.height      = 565;
            options.title       = "Options";
            options.icon        = node.path.join(node.__dirname, "assets/app-icon/png/32.png");
            options.skipTaskbar = true;
            options.parent      = Win;
            options.modal       = true;
            options.show        = false;
            options.maximizable = false;
            options.minimizable = false;
            options.resizable   = false;

            // Create the browser window.
            var optionsWin = new electron.Electron.BrowserWindow(options);

            optionsWin.setMenu(null);
            SetContextMenu(optionsWin);

            App.LoadWindow(optionsWin, "forms/OptionsForm.html");

            return(optionsWin);
        }
Example #7
0
        private static EvaluationResult GroupBy(Context context, ArrayLiteral receiver, EvaluationResult arg, EvaluationStackFrame captures)
        {
            var closure = Converter.ExpectClosure(arg);

            using (var disposableFrame = EvaluationStackFrame.Create(closure.Function, captures.Frame))
            {
                // To avoid warning: access to disposable closure.
                var frame = disposableFrame;
                var entry = context.TopStack;

                var result = receiver.Values.GroupBy(obj =>
                {
                    frame.SetArgument(0, obj);
                    return(context.InvokeClosure(closure, frame));
                });

                var arr = result.Select(grp =>
                {
                    var grpArrayLit = ArrayLiteral.CreateWithoutCopy(grp.ToArray(), entry.InvocationLocation, entry.Path);
                    var bindings    = new List <Binding>
                    {
                        new Binding(StringId.Create(context.FrontEndContext.StringTable, "key"), grp.Key, location: default(LineInfo)),
                        new Binding(StringId.Create(context.FrontEndContext.StringTable, "values"), grpArrayLit, location: default(LineInfo)),
                    };
                    return(EvaluationResult.Create(ObjectLiteral.Create(bindings, entry.InvocationLocation, entry.Path)));
                }).ToArray();

                return(EvaluationResult.Create(ArrayLiteral.CreateWithoutCopy(arr, entry.InvocationLocation, entry.Path)));
            }
        }
        private static EvaluationResult WriteFileHelper(Context context, ModuleLiteral env, EvaluationStackFrame args, WriteFileMode mode)
        {
            var path        = Args.AsPath(args, 0, false);
            var tags        = Args.AsStringArrayOptional(args, 2);
            var description = Args.AsStringOptional(args, 3);

            PipData pipData;

            switch (mode)
            {
            case WriteFileMode.WriteFile:
                var fileContent = Args.AsIs(args, 1);
                // WriteFile has a separator argument with default newline
                var separator = Args.AsStringOptional(args, 3) ?? Environment.NewLine;
                description = Args.AsStringOptional(args, 4);

                pipData = CreatePipDataForWriteFile(context, fileContent, separator);
                break;

            case WriteFileMode.WriteData:
                var data = Args.AsIs(args, 1);
                pipData = DataProcessor.ProcessData(context, context.FrontEndContext.PipDataBuilderPool, EvaluationResult.Create(data), new ConversionContext(pos: 1));
                break;

            case WriteFileMode.WriteAllLines:
                var lines   = Args.AsArrayLiteral(args, 1);
                var entry   = context.TopStack;
                var newData = ObjectLiteral.Create(
                    new List <Binding>
                {
                    new Binding(context.Names.DataSeparator, Environment.NewLine, entry.InvocationLocation),
                    new Binding(context.Names.DataContents, lines, entry.InvocationLocation),
                },
                    lines.Location,
                    entry.Path);

                pipData = DataProcessor.ProcessData(context, context.FrontEndContext.PipDataBuilderPool, EvaluationResult.Create(newData), new ConversionContext(pos: 1));
                break;

            case WriteFileMode.WriteAllText:
                var text = Args.AsString(args, 1);
                pipData = DataProcessor.ProcessData(context, context.FrontEndContext.PipDataBuilderPool, EvaluationResult.Create(text), new ConversionContext(pos: 1));
                break;

            default:
                throw Contract.AssertFailure("Unknown WriteFileMode.");
            }

            FileArtifact result;

            if (!context.GetPipConstructionHelper().TryWriteFile(path, pipData, WriteFileEncoding.Utf8, tags, description, out result))
            {
                // Error has been logged
                return(EvaluationResult.Error);
            }

            return(new EvaluationResult(result));
        }
Example #9
0
        public static void TestEventTemplate()
        {
            var person = ObjectLiteral.Create <EmployeeAndCustomer>();

            person.Type1.EmployeeId = 5;
            person.Type2.CustomerId = 3;

            Assert.AreEqual(person.Type1.EmployeeId, 5);
            Assert.AreEqual(person.Type2.CustomerId, 3);
        }
Example #10
0
        private static ObjectLiteral DeepCloneObject(ObjectLiteral obj)
        {
            var namedValues = new List <NamedValue>(obj.Count);

            foreach (var member in obj.Members)
            {
                namedValues.Add(new NamedValue(member.Key.Value, DeepCloneValue(member.Value)));
            }

            return(ObjectLiteral.Create(namedValues, obj.Location, obj.Path));
        }
Example #11
0
        /// <nodoc />
        public AmbientContext(PrimitiveTypes knownTypes)
            : base(ContextName, knownTypes)
        {
            var    currentHost = Host.Current;
            var    osName      = SymbolAtom.Create(StringTable, "os");
            string osValue;

            switch (currentHost.CurrentOS)
            {
            case BuildXL.Interop.OperatingSystem.Win:
                osValue = "win";
                break;

            case BuildXL.Interop.OperatingSystem.MacOS:
                osValue = "macOS";
                break;

            case BuildXL.Interop.OperatingSystem.Unix:
                osValue = "unix";
                break;

            default:
                throw Contract.AssertFailure("Unhandled HostOS Type");
            }

            var    cpuName = SymbolAtom.Create(StringTable, "cpuArchitecture");
            string cpuValue;

            switch (currentHost.CpuArchitecture)
            {
            case HostCpuArchitecture.X86:
                cpuValue = "x86";
                break;

            case HostCpuArchitecture.X64:
                cpuValue = "x64";
                break;

            default:
                throw Contract.AssertFailure("Unhandled CpuArchitecture Type");
            }

            var isElevatedName  = SymbolAtom.Create(StringTable, "isElevated");
            var isElevatedValue = CurrentProcess.IsElevated;

            m_currentHost = ObjectLiteral.Create(
                new Binding(osName, osValue, default(LineInfo)),
                new Binding(cpuName, cpuValue, default(LineInfo)),
                new Binding(isElevatedName, isElevatedValue, default(LineInfo))
                );

            MountNameObject = Symbol("name");
            MountPathObject = Symbol("path");
        }
Example #12
0
        private static void LoadWindow(electron.Electron.BrowserWindow win, string page)
        {
            var windowUrl = ObjectLiteral.Create <node.url.URL>();

            windowUrl.pathname = node.path.join(node.__dirname, page);
            windowUrl.protocol = "file:";

            var formattedUrl = node.url.format(windowUrl);

            // and load the index.html of the app.
            win.loadURL(formattedUrl);
        }
Example #13
0
        private static ObjectLiteral GetQualifierSpaceValue(EvaluationContext context, QualifierSpaceId qualifierSpaceId)
        {
            Contract.Requires(context != null);
            Contract.Requires(context.FrontEndContext.QualifierTable.IsValidQualifierSpaceId(qualifierSpaceId));

            var qualifierSpace = context.FrontEndContext.QualifierTable.GetQualifierSpace(qualifierSpaceId);
            var bindings       = new List <Binding>(qualifierSpace.Keys.Count);

            foreach (var kvp in qualifierSpace.AsDictionary)
            {
                var values = ArrayLiteral.CreateWithoutCopy(kvp.Value.Select(s => EvaluationResult.Create(s.ToString(context.StringTable))).ToArray(), default(LineInfo), AbsolutePath.Invalid);
                bindings.Add(new Binding(kvp.Key, values, default(LineInfo)));
            }

            return(ObjectLiteral.Create(bindings, default(LineInfo), AbsolutePath.Invalid));
        }
Example #14
0
        void UpdateUIValue()
        {
            if (_root == null)
            {
                return;
            }

            dynamic root = _root;

            dynamic options = ObjectLiteral.Create <object>();

            options.maxRating     = MaxRate;
            options.initialRating = Rate;

            Window.SetTimeout(() => { root.rating(options); }, 5);
        }
Example #15
0
        public Demo()
        {
            // Original demo:
            // http://pixijs.github.io/examples/#/demos/dragging.js

            var appOptions = ObjectLiteral.Create <IApplicationOptions>();

            appOptions.backgroundColor = 0x1099bb;

            var rootEl = dom.document.querySelector("#root");

            app = new Application(800, 600, appOptions);
            rootEl.appendChild(app.view);

            // create a new Sprite from an image path
            texture = Texture.fromImage("https://raw.githubusercontent.com/pixijs/examples/gh-pages/required/assets/bunny.png");
            texture.baseTexture.scaleMode = SCALE_MODES.NEAREST;
        }
Example #16
0
        private static electron.Electron.BrowserWindow CreateSplashScreen()
        {
            var options = ObjectLiteral.Create <electron.Electron.BrowserWindowConstructorOptions>();

            options.width       = 600;
            options.height      = 400;
            options.icon        = node.path.join(node.__dirname, "assets/app-icon/png/32.png");
            options.title       = GetAppNameWithVersion(true);
            options.frame       = false;
            options.skipTaskbar = true;
            options.show        = false;

            // Create the browser window.
            var splash = new electron.Electron.BrowserWindow(options);

            App.LoadWindow(splash, "forms/SplashScreen.html");

            return(splash);
        }
Example #17
0
        private static EvaluationResult MapWithState(Context context, ArrayLiteral receiver, EvaluationResult arg0, EvaluationResult arg1, EvaluationStackFrame captures)
        {
            var closure     = Converter.ExpectClosure(arg0);
            int paramsCount = closure.Function.Params;
            var state       = arg1;
            var arrays      = new EvaluationResult[receiver.Length];

            using (var frame = EvaluationStackFrame.Create(closure.Function, captures.Frame))
            {
                var entry = context.TopStack;

                var stateName = SymbolAtom.Create(context.FrontEndContext.StringTable, "state");
                var elemsName = SymbolAtom.Create(context.FrontEndContext.StringTable, "elems");
                var elemName  = SymbolAtom.Create(context.FrontEndContext.StringTable, "elem");

                for (int i = 0; i < receiver.Length; ++i)
                {
                    frame.TrySetArguments(paramsCount, state, receiver[i], i, EvaluationResult.Create(receiver));
                    EvaluationResult mapResult = context.InvokeClosure(closure, frame);

                    if (mapResult.IsErrorValue)
                    {
                        return(EvaluationResult.Error);
                    }

                    if (!(mapResult.Value is ObjectLiteral objectResult))
                    {
                        throw Converter.CreateException <ObjectLiteral>(mapResult, default(ConversionContext));
                    }

                    arrays[i] = objectResult[elemName];
                    state     = objectResult[stateName];
                }

                var bindings = new List <Binding>
                {
                    new Binding(elemsName, ArrayLiteral.CreateWithoutCopy(arrays, entry.InvocationLocation, entry.Path), location: default(LineInfo)),
                    new Binding(stateName, state, location: default(LineInfo)),
                };
                return(EvaluationResult.Create(ObjectLiteral.Create(bindings, entry.InvocationLocation, entry.Path)));
            }
        }
Example #18
0
        private static void CreateNotification(Tweet tweet)
        {
            var notifTitle = tweet.user.name + " is tweeting..";

            var notifOpts = ObjectLiteral.Create <dom.NotificationOptions>();

            notifOpts.body = tweet.text;
            notifOpts.icon = tweet.user.profile_image_url;

            var notif = new dom.Notification(notifTitle, notifOpts);

            notif.onclick = notifEv =>
            {
                var tweetUrl = $"https://twitter.com/{tweet.user.screen_name}/status/{tweet.id_str}";

                Electron.shell.openExternal(tweetUrl);

                return(null);
            };
        }
Example #19
0
        /// <nodoc />
        public AmbientContext(PrimitiveTypes knownTypes)
            : base(ContextName, knownTypes)
        {
            var    currentHost = Host.Current;
            var    osName      = SymbolAtom.Create(StringTable, "os");
            string osValue     = currentHost.CurrentOS.GetDScriptValue();

            if (string.IsNullOrEmpty(osValue))
            {
                throw Contract.AssertFailure("Unhandled HostOS Type");
            }

            var    cpuName = SymbolAtom.Create(StringTable, "cpuArchitecture");
            string cpuValue;

            switch (currentHost.CpuArchitecture)
            {
            case HostCpuArchitecture.X86:
                cpuValue = "x86";
                break;

            case HostCpuArchitecture.X64:
                cpuValue = "x64";
                break;

            default:
                throw Contract.AssertFailure("Unhandled CpuArchitecture Type");
            }

            var isElevatedName  = SymbolAtom.Create(StringTable, "isElevated");
            var isElevatedValue = CurrentProcess.IsElevated;

            m_currentHost = ObjectLiteral.Create(
                new Binding(osName, osValue, default(LineInfo)),
                new Binding(cpuName, cpuValue, default(LineInfo)),
                new Binding(isElevatedName, isElevatedValue, default(LineInfo))
                );

            MountNameObject = Symbol("name");
            MountPathObject = Symbol("path");
        }
Example #20
0
        private EvaluationResult IpcSend(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var obj = Args.AsObjectLiteral(args, 0);

            if (!TryScheduleIpcPip(context, obj, allowUndefinedTargetService: false, isServiceFinalization: false, out var outputFile, out _))
            {
                // Error has been logged
                return(EvaluationResult.Error);
            }


            // create and return result
            var result = ObjectLiteral.Create(
                new List <Binding>
            {
                new Binding(m_ipcSendResultOutputFile, outputFile, location: default(LineInfo)),
            },
                context.TopStack.InvocationLocation,
                context.TopStack.Path);

            return(EvaluationResult.Create(result));
        }
Example #21
0
        public object ToJson()
        {
            var instance = ObjectLiteral.Create <object>();

            foreach (var tag in Tags)
            {
                var attributes = ObjectLiteral.Create <object>();

                foreach (var attributeInfo in tag.Attributes)
                {
                    attributes[attributeInfo.Name] = attributeInfo.Values;
                }

                var tagObj = ObjectLiteral.Create <object>();
                tagObj["attrs"]    = attributes;
                tagObj["children"] = tag.ChildrenTags;

                instance[tag.Name] = tagObj;
            }

            return(instance);
        }
Example #22
0
        private EvaluationResult GetMount(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var engine = context.FrontEndHost.Engine;
            var name   = Convert.ToString(args[0].Value, CultureInfo.InvariantCulture);

            GetProvenance(context, out AbsolutePath path, out LineInfo lineInfo);

            var result = engine.TryGetMount(name, "Script", AmbientTypes.ScriptModuleId, out IMount mount);

            switch (result)
            {
            case TryGetMountResult.Success:
                return
                    (EvaluationResult.Create(ObjectLiteral.Create(
                                                 new Binding(MountNameObject, mount.Name, location: lineInfo),
                                                 new Binding(MountPathObject, mount.Path, location: lineInfo))));

            case TryGetMountResult.NameNullOrEmpty:
                throw TryGetMountException.MountNameNullOrEmpty(env, new ErrorContext(pos: 1), lineInfo);

            case TryGetMountResult.NameNotFound:
                // Check for case mismatch.
                var mountNames = engine.GetMountNames("Script", BuildXL.Utilities.ModuleId.Invalid);
                foreach (var mountName in mountNames)
                {
                    if (string.Equals(name, mountName, StringComparison.OrdinalIgnoreCase))
                    {
                        throw TryGetMountException.MountNameCaseMismatch(env, name, mountName, new ErrorContext(pos: 1), lineInfo);
                    }
                }

                throw TryGetMountException.MountNameNotFound(env, name, mountNames, new ErrorContext(pos: 1), lineInfo);

            default:
                Contract.Assume(false, "Unexpected TryGetMountResult");
                return(EvaluationResult.Undefined);
            }
        }
Example #23
0
        /// <inheritdoc/>
        protected override EvaluationResult DoEval(Context context, ModuleLiteral env, EvaluationStackFrame frame)
        {
            var result = m_expression.Eval(context, env, frame);

            if (result.IsErrorValue)
            {
                return(result);
            }

            if (!(result.Value is ModuleLiteral module))
            {
                var thisNodeType = nameof(ModuleToObjectLiteral);
                throw Contract.AssertFailure(
                          $"AstConverter should never create a '{thisNodeType}' node that wraps an expression that evaluates to something other than {nameof(ModuleLiteral)}. " +
                          $"Instead, this '{thisNodeType}' wraps an expression of type '{m_expression.GetType().Name}' which evaluated to an instance of type '{result.Value?.GetType().Name}'.");
            }

            var bindings = module
                           .GetAllBindings(context)
                           .Where(kvp => kvp.Key != Constants.Names.RuntimeRootNamespaceAlias)
                           .Select(kvp =>
            {
                var name       = SymbolAtom.Create(context.StringTable, kvp.Key);
                var location   = kvp.Value.Location;
                var evalResult = module.GetOrEvalFieldBinding(context, name, kvp.Value, location);
                return(new Binding(name, evalResult.Value, location));
            })
                           .ToArray();

            if (bindings.Any(b => b.Body.IsErrorValue()))
            {
                return(EvaluationResult.Error);
            }

            var objectLiteral = ObjectLiteral.Create(bindings);

            return(EvaluationResult.Create(objectLiteral));
        }
Example #24
0
        public static void ValidateEqual(BuildXLContext context, Type type, object expected, object actual, string objPath, Remapper remapper)
        {
            type = GetNonNullableType(type);

            if (type == typeof(bool))
            {
                XAssert.AreEqual((bool)expected, (bool)actual, $"{nameof(Boolean)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(int) || type == typeof(short) || type == typeof(sbyte) || type == typeof(long))
            {
                XAssert.AreEqual(
                    Convert.ToInt64(expected),
                    Convert.ToInt64(actual),
                    $"Numeric values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(uint) || type == typeof(ushort) || type == typeof(byte) || type == typeof(ulong))
            {
                XAssert.AreEqual(
                    Convert.ToUInt64(expected),
                    Convert.ToUInt64(actual),
                    $"Numeric values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(double))
            {
                XAssert.AreEqual(
                    Convert.ToDouble(expected),
                    Convert.ToDouble(actual),
                    $"Numeric values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(string))
            {
                XAssert.AreEqual((string)expected, (string)actual, $"{nameof(String)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(ModuleId))
            {
                XAssert.AreEqual(
                    (ModuleId)expected,
                    (ModuleId)actual,
                    $"{nameof(ModuleId)} id values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(LocationData))
            {
                AssertEqualLocationData(context, objPath, remapper, (LocationData)expected, (LocationData)actual);
                return;
            }

            if (type == typeof(RelativePath))
            {
                AssertEqualRelativePaths(context, objPath, remapper, (RelativePath)expected, (RelativePath)actual);
                return;
            }

            if (type == typeof(AbsolutePath))
            {
                AssertEqualAbsolutePaths(context, objPath, remapper, (AbsolutePath)expected, (AbsolutePath)actual);
                return;
            }

            if (type == typeof(FileArtifact))
            {
                AssertEqualFileArtifacts(context, objPath, remapper, (FileArtifact)expected, (FileArtifact)actual);
                return;
            }

            if (type == typeof(PathAtom))
            {
                AssertEqualPathAtoms(context, objPath, remapper, (PathAtom)expected, (PathAtom)actual);
                return;
            }

            if (type == typeof(SymbolAtom))
            {
                XAssert.AreEqual((SymbolAtom)expected, (SymbolAtom)actual, $"{nameof(SymbolAtom)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(global::BuildXL.Utilities.LineInfo))
            {
                XAssert.AreEqual(
                    (global::BuildXL.Utilities.LineInfo)expected,
                    (global::BuildXL.Utilities.LineInfo)actual,
                    $"{nameof(global::BuildXL.Utilities.LineInfo)} values don't match for objPath: {objPath}");
                return;
            }

            if (type == typeof(LineInfo))
            {
                XAssert.AreEqual(
                    (LineInfo)expected,
                    (LineInfo)actual,
                    $"{nameof(LineInfo)} values don't match for objPath: {objPath}");
                return;
            }

            if (type.GetTypeInfo().IsEnum)
            {
                XAssert.AreEqual((Enum)expected, (Enum)actual, $"Enum values don't match for objPath: {objPath}");
                return;
            }

            if (type.GetTypeInfo().IsGenericType)
            {
                var generic = type.GetGenericTypeDefinition();
                if (generic == typeof(List <>) || generic == typeof(IReadOnlyList <>))
                {
                    XAssert.IsTrue((expected == null) == (actual == null));

                    var expectedList = expected as IList;
                    var actualList   = actual as IList;

                    XAssert.IsTrue(
                        (expectedList == null) == (actualList == null),
                        "One of the lists is null, the other isnt for objPath: {0}",
                        objPath);
                    if (expectedList != null)
                    {
                        XAssert.AreEqual(expectedList.Count, actualList.Count, $"Counts of lists don't match for objPath: {objPath}");
                        for (int i = 0; i < expectedList.Count; i++)
                        {
                            ValidateEqual(
                                context,
                                type.GenericTypeArguments[0],
                                expectedList[i],
                                actualList[i],
                                objPath + "[" + i.ToString(CultureInfo.InvariantCulture) + "]",
                                remapper);
                        }
                    }

                    return;
                }

                if (generic == typeof(Dictionary <,>) || generic == typeof(IReadOnlyDictionary <,>) || generic == typeof(ConcurrentDictionary <,>))
                {
                    XAssert.IsTrue((expected == null) == (actual == null));

                    var expectedDictionary = expected as IDictionary;
                    var actualDictionary   = actual as IDictionary;

                    XAssert.IsTrue(
                        (expectedDictionary == null) == (actualDictionary == null),
                        $"One of the dictionaries is null, the other isnt for objPath: {objPath}");
                    if (expectedDictionary != null)
                    {
                        XAssert.AreEqual(
                            expectedDictionary.Count,
                            expectedDictionary.Count,
                            $"Counts of dictionaries don't match for objPath: {objPath}");
                        foreach (var kv in expectedDictionary)
                        {
                            var key         = kv.GetType().GetProperty("Key").GetValue(kv);
                            var value       = kv.GetType().GetTypeInfo().GetProperty("Value").GetValue(kv);
                            var actualValue = actualDictionary[key];

                            ValidateEqual(context, type.GenericTypeArguments[1], value, actualValue, objPath + "[" + key + "]", remapper);
                        }
                    }

                    return;
                }
            }

            if (type.GetTypeInfo().IsInterface)
            {
                var actualType = ConfigurationConverter.FindImplementationType(
                    type,
                    ObjectLiteral.Create(new List <Binding>(), default(LineInfo), AbsolutePath.Invalid),

                    // Note we only create a sourceresolver, so no need to fiddle, just compare with SourceResolver.
                    () => "SourceResolver");
                ValidateEqualMembers(context, actualType, expected, actual, objPath, remapper);
                return;
            }

            if (type.GetTypeInfo().IsClass)
            {
                ValidateEqualMembers(context, type, expected, actual, objPath, remapper);
                return;
            }

            XAssert.Fail($"Don't know how to compare objects of this type '{type}' for objPath: {objPath}");
        }
Example #25
0
        private static object CreateInstance(BuildXLContext context, Type type, bool booleanDefault)
        {
            string path = A("x", "path");

            type = GetNonNullableType(type);

            if (type == typeof(bool))
            {
                return(booleanDefault);
            }

            if (type == typeof(double))
            {
                return((double)0.23423);
            }

            if (type == typeof(byte))
            {
                return((byte)123);
            }

            if (type == typeof(sbyte))
            {
                return((sbyte)123);
            }

            if (type == typeof(short))
            {
                return((short)123);
            }

            if (type == typeof(ushort))
            {
                return((ushort)123);
            }

            if (type == typeof(int))
            {
                return(123);
            }

            if (type == typeof(uint))
            {
                return((uint)123);
            }

            if (type == typeof(long))
            {
                return((long)123);
            }

            if (type == typeof(ulong))
            {
                return((ulong)123);
            }

            if (type == typeof(string))
            {
                return("nonDefaultString");
            }

            if (type == typeof(ModuleId))
            {
                return(new ModuleId(123));
            }

            if (type == typeof(LocationData))
            {
                return(new LocationData(AbsolutePath.Create(context.PathTable, path), 12, 23));
            }

            if (type == typeof(AbsolutePath))
            {
                return(AbsolutePath.Create(context.PathTable, path));
            }

            if (type == typeof(RelativePath))
            {
                string relativePath = R("rel1", "dir1", "path");
                return(RelativePath.Create(context.StringTable, relativePath));
            }

            if (type == typeof(FileArtifact))
            {
                return(FileArtifact.CreateSourceFile(AbsolutePath.Create(context.PathTable, path)));
            }

            if (type == typeof(PathAtom))
            {
                return(PathAtom.Create(context.StringTable, "atom"));
            }

            if (type == typeof(global::BuildXL.Utilities.LineInfo))
            {
                return(new global::BuildXL.Utilities.LineInfo(1, 1));
            }

            if (type.GetTypeInfo().IsEnum)
            {
                bool first = true;
                foreach (var value in Enum.GetValues(type))
                {
                    if (!first)
                    {
                        return(value);
                    }

                    first = false;
                }

                XAssert.Fail($"Enum {type.FullName} doesn't have more than one value, so can't pick the second one.");
            }

            if (type.GetTypeInfo().IsGenericType)
            {
                var generic = type.GetGenericTypeDefinition();

                if (generic == typeof(IReadOnlyList <>))
                {
                    // Treat IReadOnlyList as if it was List
                    type    = typeof(List <>).MakeGenericType(type.GenericTypeArguments[0]);
                    generic = type.GetGenericTypeDefinition();
                }

                if (generic == typeof(List <>))
                {
                    var newList = (IList)Activator.CreateInstance(type);
                    newList.Add(CreateInstance(context, type.GenericTypeArguments[0], booleanDefault));
                    return(newList);
                }

                if (generic == typeof(IReadOnlyDictionary <,>))
                {
                    // Treat IReadOnlyList as if it was List
                    type    = typeof(Dictionary <,>).MakeGenericType(type.GenericTypeArguments[0], type.GenericTypeArguments[1]);
                    generic = type.GetGenericTypeDefinition();
                }

                if (generic == typeof(Dictionary <,>))
                {
                    var newDictionary = (IDictionary)Activator.CreateInstance(type);
                    newDictionary.Add(
                        CreateInstance(context, type.GenericTypeArguments[0], booleanDefault),
                        CreateInstance(context, type.GenericTypeArguments[1], booleanDefault));
                    return(newDictionary);
                }
            }

            if (type.GetTypeInfo().IsInterface)
            {
                // Treat interfaces as if it was the mutable class
                type = ConfigurationConverter.FindImplementationType(
                    type,
                    ObjectLiteral.Create(new List <Binding>(), default(LineInfo), AbsolutePath.Invalid),

                    // Return a SourceResolver to instantiate
                    () => "SourceResolver");
            }

            if (type.GetTypeInfo().IsClass)
            {
                var instance = Activator.CreateInstance(type);
                PopulateObject(context, type, instance, booleanDefault);
                return(instance);
            }

            XAssert.Fail($"Don't know how to create objects for this type: {type.FullName}.");
            return(null);
        }
Example #26
0
        private EvaluationResult WriteFileHelper(Context context, ModuleLiteral env, EvaluationStackFrame args, WriteFileMode mode)
        {
            AbsolutePath path;

            string[] tags;
            string   description;
            PipData  pipData;

            if (args.Length > 0 && args[0].Value is ObjectLiteral)
            {
                var obj = Args.AsObjectLiteral(args, 0);
                path        = Converter.ExtractPath(obj, m_writeOutputPath, allowUndefined: false);
                tags        = Converter.ExtractStringArray(obj, m_writeTags, allowUndefined: true);
                description = Converter.ExtractString(obj, m_writeDescription, allowUndefined: true);
                switch (mode)
                {
                case WriteFileMode.WriteData:
                    var data = obj[m_writeContents];
                    pipData = ProcessData(context, data, new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllLines:
                    var lines   = Converter.ExtractArrayLiteral(obj, m_writeLines);
                    var entry   = context.TopStack;
                    var newData = ObjectLiteral.Create(
                        new List <Binding>
                    {
                        new Binding(m_dataSeparator, Environment.NewLine, entry.InvocationLocation),
                        new Binding(m_dataContents, lines, entry.InvocationLocation),
                    },
                        lines.Location,
                        entry.Path);

                    pipData = ProcessData(context, EvaluationResult.Create(newData), new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllText:
                    var text = Converter.ExtractString(obj, m_writeText);
                    pipData = ProcessData(context, EvaluationResult.Create(text), new ConversionContext(pos: 1));
                    break;

                default:
                    throw Contract.AssertFailure("Unknown WriteFileMode.");
                }
            }
            else
            {
                path        = Args.AsPath(args, 0, false);
                tags        = Args.AsStringArrayOptional(args, 2);
                description = Args.AsStringOptional(args, 3);

                switch (mode)
                {
                case WriteFileMode.WriteFile:
                    var fileContent = Args.AsIs(args, 1);
                    // WriteFile has a separator argument with default newline
                    var separator = Args.AsStringOptional(args, 3) ?? Environment.NewLine;
                    description = Args.AsStringOptional(args, 4);

                    pipData = CreatePipDataForWriteFile(context, fileContent, separator);
                    break;

                case WriteFileMode.WriteData:
                    var data = Args.AsIs(args, 1);
                    pipData = ProcessData(context, EvaluationResult.Create(data), new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllLines:
                    var lines   = Args.AsArrayLiteral(args, 1);
                    var entry   = context.TopStack;
                    var newData = ObjectLiteral.Create(
                        new List <Binding>
                    {
                        new Binding(m_dataSeparator, Environment.NewLine, entry.InvocationLocation),
                        new Binding(m_dataContents, lines, entry.InvocationLocation),
                    },
                        lines.Location,
                        entry.Path);

                    pipData = ProcessData(context, EvaluationResult.Create(newData), new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllText:
                    var text = Args.AsString(args, 1);
                    pipData = ProcessData(context, EvaluationResult.Create(text), new ConversionContext(pos: 1));
                    break;

                default:
                    throw Contract.AssertFailure("Unknown WriteFileMode.");
                }
            }

            FileArtifact result;

            if (!context.GetPipConstructionHelper().TryWriteFile(path, pipData, WriteFileEncoding.Utf8, tags, description, out result))
            {
                // Error has been logged
                return(EvaluationResult.Error);
            }

            return(new EvaluationResult(result));
        }
Example #27
0
        private static void SetMainMenu()
        {
            var fileMenu = new electron.Electron.MenuItemConstructorOptions
            {
                label   = "File",
                submenu = new []
                {
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label       = "Options",
                        accelerator = CreateMenuAccelerator("F2"),
                        click       = (i, w, e) =>
                        {
                            var optionsWin = App.CreateOptionsWindow();
                            optionsWin.once(lit.ready_to_show, () =>
                            {
                                // to prevent showing not rendered window:
                                optionsWin.show();
                            });
                        }
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        type = lit.separator
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label = "Exit",
                        role  = "quit"
                    }
                }
            };

            var editMenu = new electron.Electron.MenuItemConstructorOptions
            {
                label   = "Edit",
                submenu = new[]
                {
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        role        = "undo",
                        accelerator = CreateMenuAccelerator("Ctrl+Z")
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        role        = "redo",
                        accelerator = CreateMenuAccelerator("Ctrl+Y")
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        type = lit.separator
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        role        = "cut",
                        accelerator = CreateMenuAccelerator("Ctrl+X")
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        role        = "copy",
                        accelerator = CreateMenuAccelerator("Ctrl+C")
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        role        = "paste",
                        accelerator = CreateMenuAccelerator("Ctrl+V")
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        type = lit.separator
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        role        = "selectall",
                        accelerator = CreateMenuAccelerator("Ctrl+A")
                    }
                }
            };

            var viewMenu = new electron.Electron.MenuItemConstructorOptions
            {
                label   = "View",
                submenu = new []
                {
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label       = "Reload",
                        accelerator = CreateMenuAccelerator("Ctrl+R"),
                        click       = (i, w, e) =>
                        {
                            w?.webContents.reload();
                        }
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label       = "Toggle DevTools",
                        accelerator = CreateMenuAccelerator("F12"),
                        click       = (i, w, e) =>
                        {
                            w?.webContents.toggleDevTools();
                        }
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        type = lit.separator
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label   = "Theme",
                        submenu = new []
                        {
                            new electron.Electron.MenuItemConstructorOptions
                            {
                                type     = lit.radio,
                                label    = "Light",
                                @checked = true,
                                click    = (i, w, e) =>
                                {
                                    Win.webContents.send(Constants.IPC.ToggleTheme);
                                }
                            },
                            new electron.Electron.MenuItemConstructorOptions
                            {
                                type  = lit.radio,
                                label = "Dark",
                                click = (i, w, e) =>
                                {
                                    Win.webContents.send(Constants.IPC.ToggleTheme);
                                }
                            }
                        }
                    }
                }
            };

            var captureMenu = new electron.Electron.MenuItemConstructorOptions
            {
                label   = "Capture",
                submenu = new[]
                {
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label       = "Start",
                        accelerator = CreateMenuAccelerator("F5"),
                        click       = (i, w, e) =>
                        {
                            App.ToggleStartStop(true);
                        }
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label       = "Stop",
                        accelerator = CreateMenuAccelerator("F6"),
                        enabled     = false,
                        click       = (i, w, e) =>
                        {
                            App.ToggleStartStop(false);
                        }
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        type = lit.separator
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label       = "Clear captured tweets",
                        accelerator = CreateMenuAccelerator("F7"),
                        click       = (i, w, e) =>
                        {
                            Win.webContents.send(Constants.IPC.ClearCapture);
                        }
                    }
                }
            };


            var helpMenu = new electron.Electron.MenuItemConstructorOptions
            {
                label   = "Help",
                submenu = new[]
                {
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label = "Visit Bridge.NET",
                        click = delegate
                        {
                            Electron.shell.openExternal("http://bridge.net/");
                        }
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label = "Visit Retyped",
                        click = delegate { Electron.shell.openExternal("https://retyped.com/"); }
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label = "Visit Widgetoko",
                        click = delegate { Electron.shell.openExternal("https://github.com/bridgedotnet/Widgetoko"); }
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        type = lit.separator
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label = "Visit Electron API Demos",
                        click = delegate { Electron.shell.openExternal("https://github.com/electron/electron-api-demos"); }
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label = "Visit Twitter API Reference",
                        click = delegate { Electron.shell.openExternal("https://dev.twitter.com/streaming/overview"); }
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        type = lit.separator
                    },
                    new electron.Electron.MenuItemConstructorOptions
                    {
                        label = "About",
                        click = delegate
                        {
                            var msgBoxOpts = ObjectLiteral.Create <electron.Electron.MessageBoxOptions>();
                            msgBoxOpts.type    = "info";
                            msgBoxOpts.title   = "About";
                            msgBoxOpts.buttons = new[] { "OK" };
                            msgBoxOpts.message = GetAppNameWithVersion(false) + @"

Node: " + node.process2.versions.node + @"
Chrome: " + node.process2.versions["chrome"] + @"
Electron: " + node.process2.versions["electron"];

                            Electron.dialog.showMessageBox(msgBoxOpts);
                        }
                    }
                }
            };

            var appMenu = electron.Electron.Menu.buildFromTemplate(new[] { fileMenu, editMenu, captureMenu, viewMenu, helpMenu });

            electron.Electron.Menu.setApplicationMenu(appMenu);
        }
Example #28
0
        public static Node Read(DeserializationContext context)
        {
            var reader = context.Reader;
            var kind   = (SyntaxKind)reader.ReadInt32Compact();

            // Empty node is special, because if the node is missing the only information that is stored in the stream is Kind and no location.
            if (kind == SyntaxKind.None)
            {
                return(null);
            }

            var location = LineInfo.Read(context.LineMap, reader);

            switch (kind)
            {
            case SyntaxKind.SourceFile:
                return(new SourceFile(context, location));

            case SyntaxKind.EnumMember:
                return(new EnumMemberDeclaration(context, location));

            case SyntaxKind.Parameter:
                return(new Parameter(context, location));

            case SyntaxKind.TypeParameter:
                return(new TypeParameter(context, location));

            case SyntaxKind.ApplyExpression:
                return(new NonGenericApplyExpression(context, location));

            case SyntaxKind.ApplyExpressionWithTypeArguments:
                return(new ApplyExpressionWithTypeArguments(context, location));

            case SyntaxKind.ArrayExpression:
                return(new ArrayExpression(context, location));

            case SyntaxKind.BinaryExpression:
                return(new BinaryExpression(context, location));

            case SyntaxKind.FullNameBasedSymbolReference:
                return(new FullNameBasedSymbolReference(context, location));

            case SyntaxKind.ModuleReferenceExpression:
                return(new ModuleReferenceExpression(context, location));

            case SyntaxKind.NameBasedSymbolReference:
                return(new NameBasedSymbolReference(context, location));

            case SyntaxKind.LocalReferenceExpression:
                return(new LocalReferenceExpression(context, location));

            case SyntaxKind.LocationBasedSymbolReference:
                return(new LocationBasedSymbolReference(context, location));

            case SyntaxKind.ModuleIdExpression:
                return(new ModuleIdExpression(context, location));

            case SyntaxKind.WithQualifierExpression:
                return(new WithQualifierExpression(context, location));

            case SyntaxKind.QualifierReferenceExpression:
                return(new QualifierReferenceExpression(location));

            case SyntaxKind.CoerceQualifierTypeExpression:
                return(new CoerceQualifierTypeExpression(context, location));

            case SyntaxKind.IndexExpression:
                return(new IndexExpression(context, location));

            case SyntaxKind.IteExpression:
                return(new ConditionalExpression(context, location));

            case SyntaxKind.SwitchExpression:
                return(new SwitchExpression(context, location));

            case SyntaxKind.SwitchExpressionClause:
                return(new SwitchExpressionClause(context, location));

            case SyntaxKind.LambdaExpression:
                return(new FunctionLikeExpression(context, location));

            case SyntaxKind.SelectorExpression:
                return(new SelectorExpression(context, location));

            case SyntaxKind.ResolvedSelectorExpression:
                return(new ResolvedSelectorExpression(context, location));

            case SyntaxKind.ModuleSelectorExpression:
                return(new ModuleSelectorExpression(context, location));

            case SyntaxKind.UnaryExpression:
                return(new UnaryExpression(context, location));

            case SyntaxKind.PropertyAssignment:
                return(new PropertyAssignment(context, location));

            case SyntaxKind.AssignmentExpression:
                return(new AssignmentExpression(context, location));

            case SyntaxKind.IncrementDecrementExpression:
                return(new IncrementDecrementExpression(context, location));

            case SyntaxKind.CastExpression:
                return(new CastExpression(context, location));

            case SyntaxKind.ImportAliasExpression:
                return(new ImportAliasExpression(context, location));

            case SyntaxKind.ModuleToObjectLiteral:
                return(new ModuleToObjectLiteral(context, location));

            case SyntaxKind.PathLiteral:
                return(new PathLiteral(context, location));

            case SyntaxKind.InterpolatedPaths:
                return(new InterpolatedPaths(context, location));

            case SyntaxKind.FileLiteral:
                return(new FileLiteral(context, location));

            case SyntaxKind.FileLiteralExpression:
                return(new FileLiteralExpression(context, location));

            case SyntaxKind.StringLiteralExpression:
                return(new StringLiteralExpression(context, location));

            case SyntaxKind.DirectoryLiteral:
                return(new DirectoryLiteralExpression(context, location));

            case SyntaxKind.PathAtomLiteral:
                return(new PathAtomLiteral(context, location));

            case SyntaxKind.RelativePathLiteral:
                return(new RelativePathLiteral(context, location));

            case SyntaxKind.StringLiteral:
                return(new StringLiteral(reader, location));

            case SyntaxKind.BoolLiteral:
                return(new BoolLiteral(context, location));

            case SyntaxKind.NumberLiteral:
                return(new NumberLiteral(reader, location));

            case SyntaxKind.UndefinedLiteral:
                return(UndefinedLiteral.Instance);

            case SyntaxKind.ResolvedStringLiteral:
                return(new ResolvedStringLiteral(context, location));

            case SyntaxKind.ImportDeclaration:
                return(new ImportDeclaration(context, location));

            case SyntaxKind.ExportDeclaration:
                return(new ExportDeclaration(context, location));

            case SyntaxKind.VarDeclaration:
                return(new VarDeclaration(context, location));

            case SyntaxKind.BlockStatement:
                return(new BlockStatement(context, location));

            case SyntaxKind.BreakStatement:
                return(new BreakStatement(location));

            case SyntaxKind.ContinueStatement:
                return(new ContinueStatement(location));

            case SyntaxKind.CaseClause:
                return(new CaseClause(context, location));

            case SyntaxKind.DefaultClause:
                return(new DefaultClause(context, location));

            case SyntaxKind.ExpressionStatement:
                return(new ExpressionStatement(context, location));

            case SyntaxKind.IfStatement:
                return(new IfStatement(context, location));

            case SyntaxKind.ReturnStatement:
                return(new ReturnStatement(context, location));

            case SyntaxKind.SwitchStatement:
                return(new SwitchStatement(context, location));

            case SyntaxKind.VarStatement:
                return(new VarStatement(context, location));

            case SyntaxKind.ForStatement:
                return(new ForStatement(context, location));

            case SyntaxKind.ForOfStatement:
                return(new ForOfStatement(context, location));

            case SyntaxKind.WhileStatement:
                return(new WhileStatement(context, location));

            case SyntaxKind.ArrayType:
                return(new ArrayType(context, location));

            case SyntaxKind.FunctionType:
                return(new FunctionType(context, location));

            case SyntaxKind.NamedTypeReference:
                return(new NamedTypeReference(context, location));

            case SyntaxKind.ObjectType:
                return(new ObjectType(context, location));

            case SyntaxKind.PredefinedType:
                return(new PrimitiveType(context, location));

            case SyntaxKind.TupleType:
                return(new TupleType(context, location));

            case SyntaxKind.UnionType:
                return(new UnionType(context, location));

            case SyntaxKind.TypeQuery:
                return(new TypeQuery(context, location));

            case SyntaxKind.PropertySignature:
                return(new PropertySignature(context, location));

            case SyntaxKind.CallSignature:
                return(new CallSignature(context, location));

            case SyntaxKind.TypeOrNamespaceModuleLiteral:
                return(TypeOrNamespaceModuleLiteral.Deserialize(context, location));

            case SyntaxKind.ObjectLiteral0:
            case SyntaxKind.ObjectLiteralN:
            case SyntaxKind.ObjectLiteralSlim:
                return(ObjectLiteral.Create(context, location));

            case SyntaxKind.ArrayLiteral:
                return(ArrayLiteral.Create(context, location));

            case SyntaxKind.ArrayLiteralWithSpreads:
                return(new ArrayLiteralWithSpreads(context, location));

            // Serialization is not needed for configurations.
            case SyntaxKind.ConfigurationDeclaration:
                return(new ConfigurationDeclaration(context, location));

            case SyntaxKind.PackageDeclaration:
                return(new PackageDeclaration(context, location));

            // Types are not used at runtime, so we can skip these if their serialization becomes troublesome
            case SyntaxKind.InterfaceDeclaration:
                return(new InterfaceDeclaration(context, location));

            case SyntaxKind.ModuleDeclaration:
                return(new ModuleDeclaration(context, location));

            case SyntaxKind.NamespaceImport:
                return(new NamespaceImport(context, location));

            case SyntaxKind.NamespaceAsVarImport:
                return(new NamespaceAsVarImport(context, location));

            case SyntaxKind.ImportOrExportModuleSpecifier:
                return(new ImportOrExportModuleSpecifier(context, location));

            case SyntaxKind.ImportOrExportVarSpecifier:
                return(new ImportOrExportVarSpecifier(context, location));

            case SyntaxKind.NamedImportsOrExports:
                return(new NamedImportsOrExports(context, location));

            case SyntaxKind.ImportOrExportClause:
                return(new ImportOrExportClause(context, location));

            case SyntaxKind.TypeAliasDeclaration:
                return(new TypeAliasDeclaration(context, location));

            // Enum declarations are represented as TypeOrNamespace instances at runtime
            case SyntaxKind.EnumDeclaration:
                return(new EnumDeclaration(context, location));

            // Enum members are stored as constants.
            case SyntaxKind.EnumMemberDeclaration:
                return(new EnumMemberDeclaration(context, location));

            // LambdaExpressions are serialized instead.
            case SyntaxKind.FunctionDeclaration:
                return(new FunctionDeclaration(context, location));

            // Supported only in V1 and V1 modules are not serializable.
            case SyntaxKind.QualifierSpaceDeclaration:
                return(new QualifierSpaceDeclaration(context, location));

            // Serialized separately
            case SyntaxKind.FileModuleLiteral:

            // Prelude is not serializable
            case SyntaxKind.GlobalModuleLiteral:

            // Closures are not serializable, only LambdaExpressions are
            case SyntaxKind.Closure:
            case SyntaxKind.Function0:
            case SyntaxKind.Function1:
            case SyntaxKind.Function2:
            case SyntaxKind.FunctionN:
            case SyntaxKind.BoundFunction:

            // Not serializable.
            case SyntaxKind.ImportValue:

            // Not serializable.
            case SyntaxKind.MergeModuleValue:
            case SyntaxKind.ImportExpression:
            case SyntaxKind.QualifiedLocationBasedSymbolReference:
            case SyntaxKind.ObjectLiteralOverride:

            // Added for completeness
            case SyntaxKind.None:
                break;

            // We will hit this exception if we are missing one value from the enum
            default:
                throw new BuildXLException(I($"Unable to deserialize syntax kind {kind.ToString()}"));
            }

            string message = I($"The node {kind} is not deserializable yet.");

            throw new InvalidOperationException(message);
        }
Example #29
0
        private ObjectLiteral BuildExecuteOutputs(Context context, ModuleLiteral env, ProcessOutputs processOutputs, bool isService)
        {
            var entry = context.TopStack;

            using (var empty = EvaluationStackFrame.Empty())
            {
                var getOutputFile = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetOutputFile, m_getOutputFileSignature, GetOutputFile, m_getOutputFileStatistic),
                    frame: empty);

                var getOutputDirectory = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetOutputDirectory, m_getOutputDirectorySignature, GetOutputDirectory, m_getOutputDirectoryStatistic),
                    frame: empty);

                var getOutputFiles = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetOutputFiles, m_getOutputFilesSignature, GetOutputFiles, m_getOutputFilesStatistic),
                    frame: empty);

                var getRequiredOutputFiles = new Closure(
                    env,
                    FunctionLikeExpression.CreateAmbient(ExecuteResultGetRequiredOutputFiles, m_getRequiredOutputFilesSignature, GetRequiredOutputFiles, m_getRequiredOutputFilesStatistic),
                    frame: empty);

                var bindings = new List <Binding>(isService ? 6 : 5)
                {
                    new Binding(ExecuteResultGetOutputFile, getOutputFile, location: default),
                    new Binding(ExecuteResultGetOutputDirectory, getOutputDirectory, location: default),
                    new Binding(ExecuteResultGetOutputFiles, getOutputFiles, location: default),
                    new Binding(ExecuteResultGetRequiredOutputFiles, getRequiredOutputFiles, location: default),
                    new Binding(ExecuteResultProcessOutputs, new EvaluationResult(processOutputs), location: default),
                };
                if (isService)
                {
                    bindings.Add(new Binding(CreateServiceResultServiceId, processOutputs.ProcessPipId, location: default));
                }

                return(ObjectLiteral.Create(bindings, entry.InvocationLocation, entry.Path));
            }

            // Local functions
            EvaluationResult GetOutputFile(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputPath = Args.AsPathOrUndefined(args, 0, false);

                if (outputPath.IsValid && processOutputs.TryGetOutputFile(outputPath, out var file))
                {
                    return(EvaluationResult.Create(file));
                }

                return(EvaluationResult.Undefined);
            }

            EvaluationResult GetOutputDirectory(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputDir = Args.AsDirectory(args, 0);

                if (outputDir.IsValid && processOutputs.TryGetOutputDirectory(outputDir.Path, out var output))
                {
                    return(EvaluationResult.Create(output));
                }

                return(EvaluationResult.Undefined);
            }

            EvaluationResult GetOutputFiles(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputFiles = processOutputs.GetOutputFiles().Select(f => EvaluationResult.Create(f)).ToArray();

                return(EvaluationResult.Create(ArrayLiteral.CreateWithoutCopy(outputFiles, entry.InvocationLocation, entry.Path)));
            }

            EvaluationResult GetRequiredOutputFiles(Context contextArg, ModuleLiteral envArg, EvaluationStackFrame args)
            {
                var outputFiles = processOutputs.GetRequiredOutputFiles().Select(f => EvaluationResult.Create(f)).ToArray();

                return(EvaluationResult.Create(ArrayLiteral.CreateWithoutCopy(outputFiles, entry.InvocationLocation, entry.Path)));
            }
        }
Example #30
0
 private ObjectLiteral CreateObject(string name, object value)
 {
     return(ObjectLiteral.Create(new List <Binding> {
         new Binding(CreateString(name), value ?? UndefinedValue.Instance, location: default(LineInfo))
     }, default(LineInfo), AbsolutePath.Invalid));
 }