Exemplo n.º 1
0
        public void ViewDocClick()
        {
            var packageInfo = GetSelectedPackage();

            if (packageInfo.source == PackageSource.Git)
            {
                var docsFolder = Path.Combine(packageInfo.resolvedPath, "Documentation~");
                if (!Directory.Exists(docsFolder))
                {
                    docsFolder = Path.Combine(packageInfo.resolvedPath, "Documentation");
                }
                if (Directory.Exists(docsFolder))
                {
                    var mdFiles = Directory.GetFiles(docsFolder, "*.md", SearchOption.TopDirectoryOnly);
                    var docsMd  = mdFiles.FirstOrDefault(d => Path.GetFileName(d).ToLower() == "index.md")
                                  ?? mdFiles.FirstOrDefault(d => Path.GetFileName(d).ToLower() == "tableofcontents.md") ?? mdFiles.FirstOrDefault();
                    if (!string.IsNullOrEmpty(docsMd))
                    {
                        Application.OpenURL(new Uri(docsMd).AbsoluteUri);
                        return;
                    }
                }
            }
            Expose.FromObject(GetPackageDetails()).Call("ViewDocClick");
        }
Exemplo n.º 2
0
        public PayController()
        {
            var expose = new Expose();

            _payment      = expose.CreatePayment();
            _authority    = expose.CreateAuthority();
            _transactions = expose.CreateTransactions();
        }
Exemplo n.º 3
0
        public static Dictionary <string, object> DeserializeFile(string file)
        {
            var text = File.ReadAllText(file);

#if UNITY_2019_1_9_OR_NEWER
            return(Json.Deserialize(text) as Dictionary <string, object>);
#else
            return(Expose.FromType(Type.GetType("UnityEditor.Json, UnityEditor")).Call("Deserialize", text).As <Dictionary <string, object> >());
#endif
        }
Exemplo n.º 4
0
        public BaseController(Contextdb _db, IWebHostEnvironment env)
        {
            var expose = new Expose();

            _payment      = expose.CreatePayment();
            _authority    = expose.CreateAuthority();
            _transactions = expose.CreateTransactions();
            db            = _db;
            _env          = env;
        }
Exemplo n.º 5
0
        public static void SerializeFile(string file, Dictionary <string, object> json)
        {
#if UNITY_2019_1_9_OR_NEWER
            var text = Json.Serialize(json);
#elif UNITY_2019_1_OR_NEWER
            var text = Expose.FromType(Type.GetType("UnityEditor.Json, UnityEditor")).Call("Serialize", json, false, "  ").As <string>();
#else
            var text = Expose.FromType(Type.GetType("UnityEditor.Json, UnityEditor")).Call("Serialize", json).As <string>();
#endif
            File.WriteAllText(file, text);
        }
Exemplo n.º 6
0
        public PaymentController(IAddPaymentService addPaymentService, ICartService cartService,
                                 IGetPaymentService getPaymentService, IAddNewOrderService addNewOrderService)
        {
            _addPaymentService  = addPaymentService;
            _cartService        = cartService;
            _getPaymentService  = getPaymentService;
            cookiesManager      = new CookiesManager();
            _addNewOrderService = addNewOrderService;
            //zarinpal
            var expose = new Expose();

            _payment      = expose.CreatePayment();
            _authority    = expose.CreateAuthority();
            _transactions = expose.CreateTransactions();
        }
Exemplo n.º 7
0
        public void ViewLicensesClick()
        {
            var packageInfo = GetSelectedPackage();

            if (packageInfo.source == PackageSource.Git)
            {
                var licenseFile = Path.Combine(packageInfo.resolvedPath, "LICENSE.md");
                if (File.Exists(licenseFile))
                {
                    Application.OpenURL(new Uri(licenseFile).AbsoluteUri);
                    return;
                }
            }
            Expose.FromObject(GetPackageDetails()).Call("ViewLicensesClick");
        }
Exemplo n.º 8
0
        public void ViewChangelogClick()
        {
            var packageInfo = GetSelectedPackage();

            if (packageInfo.source == PackageSource.Git)
            {
                var changelogFile = Path.Combine(packageInfo.resolvedPath, "CHANGELOG.md");
                if (File.Exists(changelogFile))
                {
                    Application.OpenURL(new Uri(changelogFile).AbsoluteUri);
                    return;
                }
            }
            Expose.FromObject(GetPackageDetails()).Call("ViewChangelogClick");
        }
Exemplo n.º 9
0
        /// <summary>
        /// On click 'Remove package' callback.
        /// </summary>
        public void RemoveClick()
        {
            Debug.LogFormat("[Bridge.UpdateClick]");
            reloading = false;
            Debug.LogFormat("[RemoveClick]");
            var selectedPackage = GetSelectedPackage();

            if (selectedPackage.source == PackageSource.Git)
            {
                PackageUtils.UninstallPackage(selectedPackage.name);
            }
            else
            {
                Expose.FromObject(packageDetails).Call("RemoveClick");
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// On click 'Update package' callback.
        /// </summary>
        public void UpdateClick()
        {
            Debug.LogFormat("[Bridge.UpdateClick]");
            reloading = false;
            var selectedPackage = GetSelectedPackage();

            if (selectedPackage.source == PackageSource.Git)
            {
                string packageId = selectedPackage.packageId;
                string url       = PackageUtils.GetRepoUrl(packageId);
#if UNITY_2019_3_OR_NEWER
                string refName = GetSelectedVersion().packageInfo.git.revision;
#else
                string refName = GetSelectedVersion().VersionId.Split('@')[1];
#endif
                PackageUtils.UninstallPackage(selectedPackage.name);
                PackageUtils.InstallPackage(selectedPackage.name, url, refName);
            }
            else
            {
                Expose.FromObject(packageDetails).Call("UpdateClick");
            }
        }
Exemplo n.º 11
0
        void UpdatePackageVersions(Package package, IEnumerable <string> versions)
        {
            Debug.LogFormat("[UpdatePackageVersions] packageName = {0}, count = {1}", package.Current.Name, versions.Count());
            var pInfo        = package.Current;
            var json         = JsonUtility.ToJson(pInfo);
            var versionInfos = versions
                               .Select(ver =>
            {
                var splited  = ver.Split(',');
                var refName  = splited[0];
                var version  = splited[1];
                var newPInfo = JsonUtility.FromJson(json, typeof(PackageInfo)) as PackageInfo;

                newPInfo.Version = SemVersion.Parse(version == refName ? version : version + "-" + refName);

                var exPackageInfo = Expose.FromObject(newPInfo);
                var memberName    = 0 < Application.unityVersion.CompareTo("2019.2") ? "IsInstalled" : "IsCurrent";
                exPackageInfo.Set(memberName, false);

                newPInfo.IsVerified = false;
                newPInfo.Origin     = (PackageSource)99;
                newPInfo.Info       = pInfo.Info;
                newPInfo.PackageId  = string.Format("{0}@{1}", newPInfo.Name, refName);
                return(newPInfo);
            })
                               .Concat(new[] { pInfo })
                               .Where(p => p == pInfo || p.Version != pInfo.Version)
                               .ToArray();

            if (0 < versionInfos.Length)
            {
                Debug.LogFormat("[UpdatePackageVersions] package source changing");
                versionInfos.OrderBy(v => v.Version).Last().IsLatest = true;
                Expose.FromObject(package).Set("source", versionInfos);
            }
        }
Exemplo n.º 12
0
 UpmPackageVersion GetSelectedVersion()
 {
     return(Expose.FromObject(packageDetails).Get("targetVersion").As <UpmPackageVersion>());
 }
Exemplo n.º 13
0
 public override Statement VisitExpose(Expose Expose)
 {
     if (Expose == null) return null;
     return base.VisitExpose((Expose)Expose.Clone());
 }
Exemplo n.º 14
0
 public virtual Statement VisitExpose(Expose expose1, Expose expose2)
 {
     if (expose1 == null) return null;
     if (expose2 == null)
     {
         expose1.Instance = this.VisitExpression(expose1.Instance, null);
         expose1.Body = this.VisitBlock(expose1.Body, null);
     }
     else
     {
         expose1.Instance = this.VisitExpression(expose1.Instance, expose1.Instance);
         expose1.Body = this.VisitBlock(expose1.Body, expose2.Body);
     }
     return expose1;
 }
Exemplo n.º 15
0
        /// <summary>
        /// Handles all mouse & keyboard events for the node.
        /// </summary>
        /// <param name="node"></param>
        public virtual void OnHandleEvents(T node)
        {
            node.editorPosition.x = Mathf.Max(node.editorPosition.x, 0f);
            node.editorPosition.y = Mathf.Max(node.editorPosition.y, 0f);
            Rect contentRect = GetContentRect(node);

            EditorGUIUtility.AddCursorRect(contentRect, MouseCursor.MoveArrow);

            if (contentRect.Contains(Event.current.mousePosition))
            {
                if (Event.current.type == EventType.ContextClick)
                {
                    // Begin Expose default method
                    if (NodifyPreferencesGUI.GetAdditionalButtons(EditorPrefs.GetInt("nodify.hotkeys.auto_create_default_method_anchor_dor_node", 303)))
                    {
                        Expose defaultExposed = null;

                        foreach (Expose exposedElement in node.GetExposed())
                        {
                            if (exposedElement.isDefault)
                            {
                                defaultExposed = exposedElement;
                            }
                        }

                        if (defaultExposed == null)
                        {
                            defaultExposed = node.GetExposedByName("OnComplete");
                        }

                        if (defaultExposed != null)
                        {
                            GameObject exposed = new GameObject(defaultExposed.exposedName);
                            exposed.hideFlags = HideFlags.HideInHierarchy;

                            Anchor anchor = exposed.AddComponent <Anchor>();
                            anchor.displayName = defaultExposed.exposedName;

                            if (defaultExposed.exposedType == ExposedType.FIELD || defaultExposed.exposedType == ExposedType.PROPERTY)
                            {
                                anchor.type = AnchorType.VARIABLE;
                            }
                            else
                            {
                                anchor.type = AnchorType.METHOD;
                            }

                            anchor.editorPosition.y = -25;

                            exposed.transform.parent = node.transform;
                        }
                    }
                    else
                    {
                        if (NodifyEditorUtilities.currentConnectingAnchor == null)
                        {
                            GenericMenu menu = new GenericMenu();
                            this.OnDrawTopContextMenu(node, menu);
                            this.OnDrawBottomContextMenu(node, menu);
                            menu.ShowAsContext();
                        }
                        else
                        {
                            if (NodifyEditorUtilities.currentConnectingAnchor.type == AnchorType.METHOD)
                            {
                                NodifyEditorUtilities.currentConnectingAnchor.ConnectToNode(node);
                                NodifyEditorUtilities.currentConnectingAnchor = null;
                            }
                        }
                    }

                    Event.current.Use();
                }

                if (Event.current.type == EventType.MouseDrag && NodifyEditorUtilities.currentDraggingAnchor == null)
                {
                    Event.current.Use();
                }

                if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
                {
                    // Handle Hot Control for input manipulation
                    if (IsSelected(node))
                    {
                        if (NodifyPreferencesGUI.GetAdditionalButtons(EditorPrefs.GetInt("nodify.hotkeys.multiple_select_and_deselect", 303)))
                        {
                            NodifyEditorWindow.RemoveFromSelectedObjects(node.gameObject);
                            NodifyEditorWindow.ForceRepaint();
                        }
                        else
                        {
                            NodifyEditorUtilities.currentManipulatingNode       = node;
                            NodifyEditorUtilities.currentManipulatingNodeOffset = node.editorPosition - Event.current.mousePosition;
                        }
                    }
                    else
                    {
                        NodifyEditorUtilities.currentManipulatingNode       = node;
                        NodifyEditorUtilities.currentManipulatingNodeOffset = node.editorPosition - Event.current.mousePosition;

                        if (NodifyPreferencesGUI.GetAdditionalButtons(EditorPrefs.GetInt("nodify.hotkeys.multiple_select_and_deselect", 303)))
                        {
                            NodifyEditorWindow.AddToSelectedObjects(node.gameObject);
                            NodifyEditorWindow.ForceRepaint();
                        }
                        else
                        {
                            Selection.activeGameObject = node.gameObject;
                        }
                    }

                    Event.current.Use();
                }
            }

            if (NodifyEditorUtilities.currentManipulatingNode == node)
            {
                Vector2 lastPosition = node.editorPosition;

                node.editorPosition = Event.current.mousePosition + NodifyEditorUtilities.currentManipulatingNodeOffset;

                Vector2 moveDelta = node.editorPosition - lastPosition;

                NodifyEditorWindow.MovedNodeSelectionDelta(node, moveDelta);
            }

            if (Event.current.type == EventType.MouseUp)
            {
                if (NodifyEditorUtilities.currentManipulatingNode == node)
                {
                    NodifyEditorUtilities.currentManipulatingNode = null;
                }
            }
        }
Exemplo n.º 16
0
    public override Statement VisitExpose(Expose Expose){
      if (Expose == null) return null;
      if (Expose.Instance == null)
        return this.VisitBlock(Expose.Body);
      TypeNode exposeInstanceType = TypeNode.StripModifiers(Expose.Instance.Type);
      if (exposeInstanceType == null)
        return this.VisitBlock(Expose.Body);
      SourceContext endContext = new SourceContext(Expose.SourceContext.Document, Expose.SourceContext.EndPos - 1, Expose.SourceContext.EndPos);

      string startMethodName = null;
      string endMethodName = null;
      Method startMethod = null;
      Method endMethod = null;

      InvariantList justToForceDeserialization = exposeInstanceType.Contract != null ? exposeInstanceType.Contract.Invariants : null;
      if (exposeInstanceType.Contract == null
        || exposeInstanceType.Contract.FramePropertyGetter == null
        ) {
        // If we're exposing an expression E of type T where T is not a guarded class,
        // then for the sake of downstream analysis tools (such as the Spec# Program Verifier) we emit the following code:
        // 
        // write|expose (E) S [alternatively, "write|expose (E at T) S"]
        //
        // is translated into
        //
        // T target = E;
        // Guard.StartWritingFrame(target, typeof(T)); [alternatively, Guard.StartWritingAtNop]
        // try{
        //   S
        // }finally{
        //   Guard.EndWritingFrame(target, typeof(T)); [alternatively, Guard.EndWritingAtNop]
        // }
        //
        // These methods are no-ops. For this reason,
        // combined with the fact that Boogie considers unchecked exceptions to be the end of the world,
        // we don't need to distinguish between checked and unchecked exceptions here.

        Block block = new Block(new StatementList());
        Local target = new Local(Identifier.Empty, exposeInstanceType, block);

        Literal typeArgument = null;
        if (Expose.IsLocal) {
          startMethodName = "StartWritingAtNop";
          endMethodName = "EndWritingAtNop";
        } else {
          startMethodName = "StartWritingFrame";
          endMethodName = "EndWritingFrame";
        }
        typeArgument = new Literal(exposeInstanceType, SystemTypes.Type);
        startMethod = 
          SystemTypes.Guard.GetMethod(Identifier.For(startMethodName), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Object), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type));
        endMethod = 
          SystemTypes.Guard.GetMethod(Identifier.For(endMethodName), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Object), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type));

        block.Statements.Add(new AssignmentStatement(target, Expose.Instance, Expose.Instance.SourceContext));
        block.Statements.Add(new ExpressionStatement(
          new MethodCall(new MemberBinding(null, startMethod), new ExpressionList(target, new UnaryExpression(typeArgument, NodeType.Typeof)),
          NodeType.Call, SystemTypes.Void), Expose.Instance.SourceContext));
        block.Statements.Add(new Try(
          Expose.Body,
          null,
          null,
          null,
          new Finally(new Block(new StatementList(new ExpressionStatement(new MethodCall(
           new MemberBinding(null, endMethod), new ExpressionList(target, new UnaryExpression(new Literal(exposeInstanceType, SystemTypes.Type), NodeType.Typeof)),
           NodeType.Call, SystemTypes.Void), endContext))))
        ));
        return (Statement) this.Visit(block);
      }

      // write|additive expose (E) S   [alternatively:  expose (E) S]
      //
      // is translated into
      //
      // Guard! rootFrame = E.FrameGuard.StartWritingTransitively(); [alternatively "StartWritingAtTransitively"]
      // Exception exception = null;
      // try {
      //     S
      // } catch (Exception e) {
      //     exception = e;
      //     throw;
      // } finally {
      //     if (exception == null || exception is ICheckedException)
      //         rootFrame.EndWritingTransitively(); [alternatively "EndWritingAtTransitively"]
      // }
      //
      // This is a hack; it would be better to statically have different code paths for
      // the normal completion case and the exceptional completion case.
      // However, that requires transforming returns, gotos, continues, breaks, etc.
      // Of course, all of the above can first be transformed into gotos.
      //
      // The "throw" in the catch clause is needed to allow the definite assignment
      // analysis to know that things assigned to in S are really assigned to
      // in the code following the finally block.
      // More importantly, who are we to eat up an exception, unless the exception
      // is checked and the object invariant doesn't hold.

      TypeNode staticInstanceType = exposeInstanceType;
      if (Expose.IsLocal) {
        startMethodName = "StartWritingAtTransitively";
        endMethodName = "EndWritingAtTransitively";
        startMethod =
          SystemTypes.Guard.GetMethod(Identifier.For(startMethodName), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type));
        endMethod =
          SystemTypes.Guard.GetMethod(Identifier.For(endMethodName), OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type));
      } else {
        if (Expose.NodeType == NodeType.Read) {
          startMethodName = "StartReadingTransitively";
          endMethodName = "EndReadingTransitively";
        } else {
          startMethodName = "StartWritingTransitively";
          endMethodName = "EndWritingTransitively";
        }
        startMethod = SystemTypes.Guard.GetMethod(Identifier.For(startMethodName));
        endMethod = SystemTypes.Guard.GetMethod(Identifier.For(endMethodName));
      }

      TypeNode guardType = OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Guard);
      Method frameGetter = staticInstanceType.Contract.FramePropertyGetter;

      Block newBody = new Block();
      Local rootFrame = new Local(Identifier.For("SS$rootFrame"), guardType, newBody);
      Expression frameGetterCall = new MethodCall(new MemberBinding(Expose.Instance, frameGetter), null);

      // Need two independent argument lists. Otherwise, the processing of the first one disrupts the
      // second one.
      ExpressionList startFrameGetterExprArgs;
      ExpressionList endFrameGetterExprArgs;
      if (Expose.IsLocal) {
        startFrameGetterExprArgs = new ExpressionList(new UnaryExpression(new Literal(exposeInstanceType, SystemTypes.Type), NodeType.Typeof));
        endFrameGetterExprArgs = new ExpressionList(new UnaryExpression(new Literal(exposeInstanceType, SystemTypes.Type), NodeType.Typeof));
      } else {
        startFrameGetterExprArgs = null;
        endFrameGetterExprArgs = null;
      }
      Expression frameGetterExpr = new MethodCall(new MemberBinding(frameGetterCall, startMethod), startFrameGetterExprArgs, NodeType.Call, startMethod.ReturnType);

      Statement startCall = new AssignmentStatement(rootFrame, frameGetterExpr, Expose.Instance.SourceContext);

      // rootFrame.End(Reading|Writing)Transitively();
      Statement endCall = new ExpressionStatement(new MethodCall(new MemberBinding(rootFrame, endMethod), endFrameGetterExprArgs, NodeType.Call, SystemTypes.Void), endContext);
      Local exception = new Local(SystemTypes.Exception);
      CatchList catchList = new CatchList(1);
      Throw rethrow = new Throw();
      rethrow.NodeType = NodeType.Rethrow;
      Local e = new Local(SystemTypes.Exception);
      catchList.Add(new Catch(new Block(new StatementList(new AssignmentStatement(exception, e), rethrow)), e, SystemTypes.Exception));
      newBody.Statements = new StatementList(
        startCall,
        new AssignmentStatement(exception, new Literal(null, SystemTypes.Exception)),
        new Try(
        Expose.Body,
        catchList,
        null, null,
        new Finally(new Block(new StatementList(
        new If(
          new BinaryExpression(
            new BinaryExpression(exception, new Literal(null, SystemTypes.Exception), NodeType.Eq, SystemTypes.Boolean),
            new BinaryExpression(exception, new Literal(SystemTypes.ICheckedException, SystemTypes.Type), NodeType.Is, SystemTypes.Boolean),
            NodeType.LogicalOr,
            SystemTypes.Boolean),
        new Block(new StatementList(endCall)),
        null))))));
      return this.VisitBlock(newBody);
    }
Exemplo n.º 17
0
    public override Method VisitMethod(Method method) {
      if (method == null) return null;
      if (method.IsNormalized) return method;
      this.MayReferenceThisAndBase = !(method is InstanceInitializer) || method.DeclaringType == null || method.DeclaringType.IsValueType;
      if (method.Name != null && method.Name.UniqueIdKey == StandardIds.Finalize.UniqueIdKey && method.HasCompilerGeneratedSignature &&
        method.DeclaringType is Class && ((Class)method.DeclaringType).IsAbstractSealedContainerForStatics)
        this.HandleError(method.Name, Error.DestructorInAbstractSealedClass);
      method.Attributes = this.VisitAttributeList(method.Attributes, method);
      method.ReturnAttributes = this.VisitAttributeList(method.ReturnAttributes);
      method.SecurityAttributes = this.VisitSecurityAttributeList(method.SecurityAttributes);
      if ((method.ReturnType == SystemTypes.DynamicallyTypedReference || method.ReturnType == SystemTypes.ArgIterator) && 
      (this.currentOptions == null || !this.currentOptions.NoStandardLibrary) ) {
        this.HandleError(method.Name, Error.CannotReturnTypedReference, this.GetTypeName(method.ReturnType));
        method.ReturnType = SystemTypes.Object;
      }
      if (method.Body != null) {
        if (method.DeclaringType is Interface && !method.IsStatic) {
          this.HandleError(method.Name, Error.InterfaceMemberHasBody, this.GetMethodSignature(method));
          method.Body = null;
        } else if (method.IsAbstract) {
          this.HandleError(method.Name, Error.AbstractHasBody, this.GetMethodSignature(method));
          method.Body = null;
        }
      } else if (!method.IsAbstract && !method.IsExtern && !this.isCompilingAContractAssembly) {
        this.HandleError(method.Name, Error.ConcreteMissingBody, this.GetMethodSignature(method));
        return null;
      } else if (method.TemplateParameters != null && method.TemplateParameters.Count > 0 && !this.useGenerics) {
        SourceContext ctx = method.TemplateParameters[0].SourceContext;
        ctx.EndPos = method.TemplateParameters[method.TemplateParameters.Count-1].SourceContext.EndPos;
        Debug.Assert(ctx.EndPos >= ctx.StartPos);
        Node n = new UnaryExpression();
        n.SourceContext = ctx;
        if (method.DeclaringType is Interface)
          this.HandleError(n, Error.AbstractInterfaceMethod);
        else
          this.HandleError(n, Error.AbstractMethodTemplate);
        return null;
      }
      BlockScope savedCurrentFinallyClause = this.currentFinallyClause;
      Method savedCurrentMethod = this.currentMethod;
      Return savedReturnNode = this.returnNode;
      Yield savedYieldNode = this.yieldNode;
      this.currentFinallyClause = null;
      this.currentMethod = method;
      this.returnNode = null;
      this.yieldNode = null;
      MethodScope scope = method.Scope;
      this.CheckForDuplicateDeclarations(scope);

      if ((this.currentPreprocessorDefinedSymbols != null && this.currentPreprocessorDefinedSymbols.ContainsKey("DefaultExposeBlocks")) &&
        !method.IsStatic && !(method is InstanceInitializer) && method.DeclaringType is Class && 
        !method.IsAbstract && method.CciKind == CciMemberKind.Regular && method.ApplyDefaultContract) {
        This thisOb = method.ThisParameter;
        MethodCall thisIsExposable = new MethodCall(
          new MemberBinding(null, SystemTypes.Guard.GetMethod(Identifier.For("FrameIsExposable"),
            SystemTypes.Object, SystemTypes.Type)),
            new ExpressionList(thisOb, new UnaryExpression(new Literal(method.DeclaringType, SystemTypes.Type),
            NodeType.Typeof, OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type))), NodeType.Call,
            SystemTypes.Boolean, method.Body.SourceContext);
        Assumption assumption = new Assumption(thisIsExposable);
        Expose expose = new Expose(NodeType.Write);
        expose.SourceContext = method.Body.SourceContext;
        expose.Instance = thisOb;
        expose.Body = method.Body;
        if (this.currentOptions != null && this.currentOptions.DisableGuardedClassesChecks)
          method.Body = new Block(new StatementList(assumption, expose));
        else
          method.Body = new Block(new StatementList(expose));
      }


      #region Check contract rules for all interface methods and base methods this method implements/overrides
      bool ok = true;
      if (method.IsVirtual && !method.IsCompilerControlled) {
        // use FindNearest..., can't rely on method.OverriddenMethod since it might not be set further up the chain
        Method overridden = method.DeclaringType.FindNearestOverriddenMethod(method);
        if (overridden != null) {
          ok &= this.CheckContractRules(overridden, method, method.DeclaringType);
        }
        for (int i = 0, n = method.ImplementedInterfaceMethods == null ? 0 : method.ImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplementedInterfaceMethods[i];
          ok &= this.CheckContractRules(ifaceMethod, method, method.DeclaringType);
        }
        for (int i = 0, n = method.ImplicitlyImplementedInterfaceMethods == null ? 0 : method.ImplicitlyImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplicitlyImplementedInterfaceMethods[i];
          ok &= this.CheckContractRules(ifaceMethod, method, method.DeclaringType);
        }
      }
      #endregion

      #region Contract Inheritance for method overrides and interface implementations (do this somewhere else?)
      // This needs to be done here (and not in VisitMethodContract) because method might not even have a contract
      if (method.IsVirtual && ok && !method.IsCompilerControlled) {
        // use FindNearest..., can't rely on method.OverriddenMethod since it might not be set further up the chain
        Method overridden = method.DeclaringType.FindNearestOverriddenMethod(method);
        // FindNearestOverriddenMethod doesn't care if method is "new" or an "override", so explicity test IsVirtual property
        MethodContract cumulativeContract = method.Contract == null ? new MethodContract(method) : method.Contract;
        bool somethingWasCopied = false;
        while (overridden != null && overridden.IsVirtual) {
          if (overridden.Contract != null) {
            cumulativeContract.CopyFrom(overridden.Contract);
            somethingWasCopied = true;
            break;
          }
          overridden = overridden.DeclaringType.FindNearestOverriddenMethod(overridden);
        }
        // Can inherit from at most one interface method
        bool ifaceContractWasCopied = false;
        for (int i = 0, n = method.ImplementedInterfaceMethods == null ? 0 : method.ImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplementedInterfaceMethods[i];
          if (ifaceMethod == null) continue;
          if (ifaceMethod.Contract != null) {
            if (ifaceContractWasCopied) {
              this.HandleError(method, Error.RequiresNotAllowedInInterfaceImplementation, this.GetMethodSignature(ifaceMethod));
              break;
            }
            cumulativeContract.CopyFrom(ifaceMethod.Contract);
            somethingWasCopied = true;
            ifaceContractWasCopied = true;
          }
        }
        for (int i = 0, n = method.ImplicitlyImplementedInterfaceMethods == null ? 0 : method.ImplicitlyImplementedInterfaceMethods.Count; i < n; i++) {
          Method ifaceMethod = method.ImplicitlyImplementedInterfaceMethods[i];
          if (ifaceMethod == null) continue;
          if (ifaceMethod.Contract != null) {
            if (ifaceContractWasCopied) {
              this.HandleError(method, Error.RequiresNotAllowedInInterfaceImplementation, this.GetMethodSignature(ifaceMethod));
              break;
            }
            cumulativeContract.CopyFrom(ifaceMethod.Contract);
            somethingWasCopied = true;
            ifaceContractWasCopied = true;
          }
        }
        if (method.Contract == null && somethingWasCopied) { // otherwise it was already copied into the method's contract 
          method.Contract = cumulativeContract;
        }
      }
      #endregion
      
      // For checked exceptions, the actual exceptions thrown must be a subset of the allowed exceptions
      TypeNodeList aes = new TypeNodeList();
      if (method.Contract != null && method.Contract.Ensures != null) {
        for (int i = 0, n = method.Contract.Ensures.Count; i < n; i++) {
          EnsuresExceptional ee = method.Contract.Ensures[i] as EnsuresExceptional;
          if (ee == null || ee.Inherited) continue;
          aes.Add(ee.Type);
        }
      }
      TypeNodeList saveAllowedExceptions = this.allowedExceptions;
      this.allowedExceptions = aes;
      // don't check method body of proxy methods.
      Method result = (method is ProxyMethod) ? method : base.VisitMethod(method);
      this.allowedExceptions = saveAllowedExceptions;


      if (this.yieldNode != null && TypeNode.StripModifiers(method.ReturnType) is Interface) {
        StatementList statements = new StatementList(1);
        TypeNode elementType = SystemTypes.Object;
        Interface stype = (Interface)TypeNode.StripModifiers(method.ReturnType);
        if (stype.TemplateArguments != null && stype.TemplateArguments.Count == 1) elementType = stype.TemplateArguments[0];
        Class state = scope.ClosureClass;
        elementType = scope.FixTypeReference(elementType);
        state.Flags |= TypeFlags.Abstract; //So that no complaints are given about missing methods added by Normalizer
        state.Interfaces = new InterfaceList(5);
        state.Interfaces.Add(SystemTypes.IEnumerable);
        state.Interfaces.Add((Interface)SystemTypes.GenericIEnumerator.GetTemplateInstance(this.currentType, elementType));
        state.Interfaces.Add(SystemTypes.IEnumerator);
        state.Interfaces.Add(SystemTypes.IDisposable);
        state.Interfaces.Add((Interface)SystemTypes.GenericIEnumerable.GetTemplateInstance(this.currentType, elementType));
        //Add these methods so that Normalizer can find them even when reference to iterator is forward
        Method moveNext = new Method(state, null, StandardIds.MoveNext, null, SystemTypes.Boolean, null);
        moveNext.CallingConvention = CallingConventionFlags.HasThis;
        moveNext.Flags = MethodFlags.Public|MethodFlags.Virtual;
        moveNext.Body = new Block(new StatementList());
        state.Members.Add(moveNext);
        Method getCurrent = new Method(state, null, StandardIds.getCurrent, null, elementType, null);
        getCurrent.CallingConvention = CallingConventionFlags.HasThis;
        getCurrent.Flags = MethodFlags.Public|MethodFlags.Virtual|MethodFlags.SpecialName;
        getCurrent.Body = new Block(new StatementList());
        state.Members.Add(getCurrent);
        Return ret = new Return(new ConstructIterator(state, method.Body, elementType, state));
        if (method.Name.SourceContext.Document != null) {
          ret.SourceContext = method.SourceContext;
          ret.SourceContext.EndPos = method.Name.SourceContext.EndPos;
          Debug.Assert(ret.SourceContext.EndPos >= ret.SourceContext.StartPos);
        }
        statements.Add(ret);
        method.Body = new Block(statements);
        method.Body.Scope = new BlockScope(scope, method.Body);
      }
      if (method.IsStatic && method.IsVirtual && !method.IsSpecialName) {
        method.Flags &= ~MethodFlags.Static;
        this.HandleError(method.Name, Error.StaticNotVirtual, this.GetMethodSignature(method));
      }
      if (!method.OverridesBaseClassMember) {
        if (method.NodeType == NodeType.InstanceInitializer || !method.IsSpecialName) {
          if (!(method.DeclaringType is Interface) && !(method.DeclaringType is DelegateNode)) {
            if (this.IsLessAccessible(method.ReturnType, method)) {
              this.HandleError(method.Name, Error.ReturnTypeLessAccessibleThanMethod, this.GetTypeName(method.ReturnType), this.GetMethodSignature(method));
              this.HandleRelatedError(method.ReturnType);
            }
            this.CheckParameterTypeAccessibility(method.Parameters, method);
          }
        } else {
          if (method.Name != null && Checker.OperatorName[method.Name.UniqueIdKey] != null) {
            if (this.IsLessAccessible(method.ReturnType, method)) {
              this.HandleError(method.Name, Error.ReturnTypeLessAccessibleThanOperator, this.GetTypeName(method.ReturnType), this.GetMethodSignature(method));
              this.HandleRelatedError(method.ReturnType);
            }
            this.CheckParameterTypeAccessibility(method.Parameters, method);
          }
        }
      }

      if (!method.IsSpecialName) {
        TypeNodeList implementedTypes = method.ImplementedTypes;
        if (implementedTypes != null) {
          InterfaceList declaringTypeInterfaces = this.GetTypeView(method.DeclaringType).Interfaces;
          for (int i = 0, n = implementedTypes.Count; i < n; i++) {
            Interface iface = implementedTypes[i] as Interface;
            if (iface == null) continue;
            if (!this.IsAllowedAsImplementedType(declaringTypeInterfaces, iface)) {
              Node offendingNode = method.ImplementedTypeExpressions[i];
              this.HandleError(offendingNode, Error.ContainingTypeDoesNotImplement, this.GetMethodSignature(method), this.GetTypeName(iface));
              this.HandleRelatedError(iface);
              implementedTypes = null;
              break;
            }
          }
        }
        MethodList implementedMethods = method.ImplementedInterfaceMethods;
        for (int i = 0, n = implementedTypes == null ? 0 : implementedTypes.Count; i < n; i++) {
          Interface iface = implementedTypes[i] as Interface;
          if (iface == null) continue;
          Method m = implementedMethods == null ? null : implementedMethods[i];
          if (m == null) {
            this.HandleError(method.Name, Error.InterfaceMemberNotFound, this.GetMemberSignature(method), this.GetTypeName(iface));
            this.HandleRelatedError(iface);
          } else if (m.IsSpecialName)
            this.HandleError(method.Name, Error.CannotExplicitlyImplementAccessor, this.GetMethodSignature(method), this.GetMethodSignature(m));
        }
      }
      if ((method.Flags & MethodFlags.PInvokeImpl) != 0) {
        Error e = Error.None;
        if (this.shadowedAssembly != null) {
          // Make sure this method has a counterpart in the shadowed method
          TypeNode type = this.GetCorrespondingShadowedTypeNode(method.DeclaringType);
          if (type == null) {
            this.HandleError(method.DeclaringType, Error.TypeMissingInShadowedAssembly, this.GetTypeName(method.DeclaringType));
          } else {
            int numParams = method.Parameters == null ? 0 : method.Parameters.Count;
            TypeNode[] types = new TypeNode[numParams];
            for (int i = 0; i < numParams; i++) { types[i] = this.GetCorrespondingShadowedTypeNode(TypeNode.StripModifiers(method.Parameters[i].Type)); }
            if (this.GetTypeView(type).GetMethod(method.Name, types) == null) {
              this.HandleError(method, Error.MethodMissingInShadowedAssembly, this.GetMethodSignature(method));
            }
          }
        } else if (this.isCompilingAContractAssembly)
          e = Error.None;
        else if (method.Body != null)
          e = Error.PInvokeHasBody;
        else if (method.IsAbstract)
          e = Error.AbstractAndExtern;
        else if (method.PInvokeImportName == null || method.PInvokeModule == null) {
          if (method.Attributes == null || method.Attributes.Count == 0)
            e = Error.PInvokeWithoutModuleOrImportName;
          else
            method.Flags &= ~MethodFlags.PInvokeImpl;
        }
        if (e != Error.None)
          this.HandleError(method.Name, e, this.GetMethodSignature(method));
      }
      if (method.IsPropertySetter && (method.IsPure || method.IsConfined || method.IsStateIndependent)) {
        this.HandleError(method, Error.MemberCannotBeAnnotatedAsPure, this.GetMethodSignature(method));
      }
      this.currentFinallyClause = savedCurrentFinallyClause;
      this.currentMethod = savedCurrentMethod;
      this.returnNode = savedReturnNode;
      this.yieldNode = savedYieldNode;
      return result;
    }
Exemplo n.º 18
0
 public virtual void VisitExpose(Expose @expose)
 {
   if (@expose == null) return;
   this.VisitExpression(@expose.Instance);
   this.VisitBlock(expose.Body);
 }
Exemplo n.º 19
0
        /// <summary>
        /// Update package info.
        /// </summary>
#if UNITY_2019_3_OR_NEWER
        void UpdatePackageVersions(UpmPackage package, IEnumerable <string> versions)
        {
            var pInfo = package.installedVersion as UpmPackageVersion;
            var json  = JsonUtility.ToJson(pInfo.packageInfo);

            string packageName, repoUrl, installedRefName;

            PackageUtils.SplitPackageId(pInfo.uniqueId, out packageName, out repoUrl, out installedRefName);

            Debug.LogFormat("[UpdatePackageVersions] packageName = {0}, count = {1}, current = {2}", package.name, versions.Count(), pInfo.version);
            var versionInfos = versions
                               .Select(ver =>
            {
                Debug.LogFormat("[UpdatePackageVersions] version = {0}", ver);
                var splited = ver.Split(',');
                var refName = splited[0];
                var version = splited[1];
                var semver  = SemVersion.Parse(version == refName ? version : version + "-" + refName);

                var info = JsonUtility.FromJson <PackageInfo>(json);
                Expose.FromObject(info).Set("m_Version", version);
                Expose.FromObject(info).Set("m_Git", new GitInfo("", refName));

                var p = new UpmPackageVersion(info, false, semver, pInfo.displayName);

                // Update tag.
                PackageTag tag = PackageTag.Git | PackageTag.Installable | PackageTag.Removable;
                if ((semver.Major == 0 && string.IsNullOrEmpty(semver.Prerelease)) ||
                    PackageTag.Preview.ToString().Equals(semver.Prerelease.Split('.')[0], StringComparison.InvariantCultureIgnoreCase))
                {
                    tag |= PackageTag.Preview;
                }

                if (semver.IsRelease())
                {
                    tag |= PackageTag.Release;
                }
                else
                {
                    if ((semver.Major == 0 && string.IsNullOrEmpty(semver.Prerelease)) ||
                        PackageTag.Preview.ToString().Equals(semver.Prerelease.Split('.')[0], StringComparison.InvariantCultureIgnoreCase))
                    {
                        tag |= PackageTag.Preview;
                    }
                }

                Expose.FromObject(p).Set("m_Tag", tag);
                Expose.FromObject(p).Set("m_IsFullyFetched", true);
                Expose.FromObject(p).Set("m_PackageId", string.Format("{0}@{1}#{2}", packageName, repoUrl, semver));

                return(p);
            })
                               .Concat(new[] { pInfo })
                               .Where(p => p == pInfo || p.version != pInfo.version)
                               .OrderBy(x => x.version)
                               .ToArray();

            if (0 < versionInfos.Length)
            {
                // Add verify tag on latest version.
                var latest = versionInfos
                             .Where(x => x.version.IsRelease())
                             .LastOrDefault();
                if (latest != null)
                {
                    var tag = Expose.FromObject(latest).Get("m_Tag").As <PackageTag>();
                    tag |= PackageTag.Verified;
                    Expose.FromObject(latest).Set("m_Tag", tag);
                }

                // Unlock version tag.
                var t = Expose.FromObject(pInfo).Get("m_Tag").As <PackageTag>();
                Expose.FromObject(pInfo).Set("m_Tag", t & ~PackageTag.VersionLocked);

                Debug.LogFormat("[UpdatePackageVersions] package source changing");
                package.UpdateVersions(versionInfos);
            }
        }
Exemplo n.º 20
0
 public override Statement VisitExpose(Expose Expose) {
   if (Expose == null) return null;
   Expression e = this.VisitExpression(Expose.Instance);
   if (e == null) return null;
   Expression g = Expose.Instance = e;
   TypeNode exprT = this.typeSystem.Unwrap(g.Type);
   if (exprT != null && !(exprT is Class || exprT is Struct)) //WS needs right error code
     this.HandleError(g, Error.OnlyStructsAndClassesCanHaveInvariants, this.GetTypeName(exprT));
   if (exprT == null)
     exprT = SystemTypes.Object;
   Expose.Body = this.VisitBlock(Expose.Body);
   return Expose;
 }
Exemplo n.º 21
0
 PackageInfo GetSelectedVersion()
 {
     return(Expose.FromObject(packageDetails).Get("SelectedPackage").As <PackageInfo>());
 }
Exemplo n.º 22
0
 public virtual Statement VisitExpose(Expose @expose){
   if (@expose == null) return null;
   @expose.Instance = this.VisitExpression(@expose.Instance);
   @expose.Body = this.VisitBlock(expose.Body);
   return expose;
 }
Exemplo n.º 23
0
 public override Statement VisitExpose(Expose Expose){
   if (Expose == null) return null;
   Expose.Instance = this.VisitExpression(Expose.Instance);
   Expose.Body = this.VisitBlock(Expose.Body);
   return Expose;
 }