public SymbolLookup Add(string name, IdentifierKind kind, string classType)
        {
            SymbolLookup symbol = null;

            if (IsFieldOrStatic(kind))
            {
                int number = classSymbols.Count(s => s.Kind == kind);
                symbol = new SymbolLookup {
                    Name = name, Kind = kind, Number = number, ClassType = classType
                };
                classSymbols.Add(symbol);
            }
            if (IsArgumentOrVar(kind))
            {
                int number = subroutineSymbols.Count(s => s.Kind == kind);
                if (isMethod && kind == IdentifierKind.Argument)
                {
                    number++;
                }
                symbol = new SymbolLookup {
                    Name = name, Kind = kind, Number = number, ClassType = classType
                };
                subroutineSymbols.Add(symbol);
            }
            return(symbol);
        }
        public Node ParseClassVariableDeclaration()
        {
            var            cvd  = new Node(NodeType.ClassVariableDeclaration);
            IdentifierKind kind = Peek() == "static" ? IdentifierKind.Static : IdentifierKind.Field;

            DequeueKeyword(cvd);
            string className = DequeueType(cvd);
            bool   another;

            do
            {
                DequeueIdentifierDeclaration(cvd, kind, className, "class static or field declaration expected a variable name");
                another = Peek() == ",";
                if (another)
                {
                    cvd.AddChild(tokens.Dequeue());
                }
            } while (another);
            DequeueSymbol(cvd, ";");
            return(cvd);
        }
        private void DequeueIdentifierDeclaration(Node parent, IdentifierKind kind, string classType, string error)
        {
            Token token = Dequeue();

            if (token?.Type == NodeType.Identifier)
            {
                Identifier identifier;
                if (SymbolTable.IsClassOrSubroutine(kind))
                {
                    identifier = new Identifier(token.Value, kind, true);
                }
                else
                {
                    SymbolLookup symbolLookup = symbolTable.Add(token.Value, kind, classType);
                    if (symbolLookup != null)
                    {
                        identifier = new Identifier(symbolLookup.Name, symbolLookup.Kind, true, symbolLookup.Number);
                    }
                    else
                    {
                        identifier = new Identifier(token.Value, IdentifierKind.Subroutine, true);
                    }
                }
                identifier.ClassType = classType;
                parent.AddChild(identifier);
                if (Peek() == "[")
                {
                    DequeueSymbol(parent, "[");
                    parent.AddChild(ParseExpression());
                    DequeueSymbol(parent, "]");
                }
            }
            else
            {
                string suffix = token == null ? ", reached end of file instead" : $", got {token} instead";
                throw new ApplicationException(error + suffix);
            }
        }
Exemple #4
0
        ///////////////////////////////////////////////////////////////////////

        private /* protected virtual */ void Dispose(
            bool disposing
            )
        {
            if (!disposed)
            {
                if (disposing)
                {
                    ////////////////////////////////////
                    // dispose managed resources here...
                    ////////////////////////////////////

                    if (children != null)
                    {
                        foreach (INamespace child in children.Values)
                        {
                            if (child == null)
                            {
                                continue;
                            }

                            IDisposable disposable = child as IDisposable;

                            if (disposable != null)
                            {
                                disposable.Dispose();
                                disposable = null;
                            }
                        }

                        children.Clear();
                        children = null;
                    }

                    ///////////////////////////////////////////////////////////

                    if (exportNames != null)
                    {
                        exportNames.Clear();
                        exportNames = null;
                    }

                    ///////////////////////////////////////////////////////////

                    if (imports != null)
                    {
                        ReturnCode removeCode;
                        Result     removeError = null;

                        removeCode = RemoveImports(
                            null, false, ref removeError);

                        if (removeCode != ReturnCode.Ok)
                        {
                            DebugOps.Complain(
                                interpreter, removeCode, removeError);
                        }

                        imports.Clear();
                        imports = null;
                    }

                    ///////////////////////////////////////////////////////////

                    if (interpreter != null)
                    {
                        interpreter = null; /* NOT OWNED */
                    }
                    ///////////////////////////////////////////////////////////

                    parent  = null; /* NOT OWNED */
                    resolve = null; /* NOT OWNED */

                    ///////////////////////////////////////////////////////////

                    if (variableFrame != null)
                    {
                        variableFrame.Free(true);
                        variableFrame = null;
                    }

                    ///////////////////////////////////////////////////////////

                    unknown = null;

                    ///////////////////////////////////////////////////////////

                    qualifiedName  = null;
                    referenceCount = 0;
                    deleted        = false;

                    ///////////////////////////////////////////////////////////

                    kind        = IdentifierKind.None;
                    id          = Guid.Empty;
                    name        = null;
                    group       = null;
                    description = null;
                    clientData  = null;
                }

                //////////////////////////////////////
                // release unmanaged resources here...
                //////////////////////////////////////

                disposed = true;
            }
        }
Exemple #5
0
        /// <summary>
        /// Resolve the identifier meaning
        /// </summary>
        public void Resolve(Emitter.Emitter emitter)
        {
            // already resolved?
              if (Kind != IdentifierKind.Unresolved) return;

              // atmark?
              if (AtmarkPrefix)
              {
            if (emitter.CurrentType == null)
              Error(Resources.errFieldOutsideType);

            OwnerType = emitter.CurrentType.Name;

            var field = emitter.FindField(emitter.CurrentType.Name, Name);
            if (field != null)
              Kind = field.Static ? IdentifierKind.StaticField : IdentifierKind.Field;
            else
              Error(String.Format(Resources.errFieldNotFound, Name, emitter.CurrentType.Name));

            // additional check: dynamic field from static method
            if (emitter.CurrentMethod.Static && !field.Static)
              Error(String.Format(Resources.errDynamicFromStatic, field.Name));
              }

              // other prefix?
              else if (TypePrefix != null || ExpressionPrefix != null)
              {
            OwnerType = (TypePrefix != null ? TypePrefix.Data : ExpressionPrefix.GetExpressionType(emitter));

            if (OwnerType == "null")
              Error(Resources.errNullAccessor);

            if(OwnerType.EndsWith("[]") && Name == "size")
            {
              Kind = IdentifierKind.SizeProperty;
              return;
            }

            // check class existence
            emitter.FindType(OwnerType);

            // field ?
            try
            {
              emitter.FindField(OwnerType, Name);
              Kind = (TypePrefix != null ? IdentifierKind.StaticField : IdentifierKind.Field);
              return;
            }
            catch { }

            // method ?!
            MethodNode method = null;
            try
            {
              method = emitter.FindMethod(OwnerType, Name);
            }
            catch
            {
              Error(String.Format(Resources.errTypeIdentifierUnresolved, OwnerType, Name));
            }

            if (ExpressionPrefix == null && !method.Static)
              Error(String.Format(Resources.errNonStaticMethod, Name));

            Kind = (TypePrefix != null ? IdentifierKind.StaticMethod : IdentifierKind.Method);
              }

              else
              {
            MethodNode method = null;

            // local variable
            if (emitter.CurrentMethod.Scope.Exists(Name))
            {
              Kind = IdentifierKind.Variable;
              return;
            }

            // parameter
            if(emitter.CurrentMethod.Parameters.Contains(Name))
            {
              Kind = IdentifierKind.Parameter;
              return;
            }

            // search for a method
            try
            {
              method = emitter.FindMethod(emitter.CurrentType != null ? emitter.CurrentType.Name : "", true, Name);
            }
            catch
            {
              Error(String.Format(Resources.errIdentifierUnresolved, Name));
            }

            OwnerType = method.Owner.Name;
            if(method.Static)
              Kind = IdentifierKind.StaticMethod;
            else
            {
              // additional check for invoking a dynamic method from static context
              if (emitter.CurrentMethod == null || emitter.CurrentMethod.Static)
            Error(String.Format(Resources.errDynamicFromStatic, Name));

              Kind = IdentifierKind.Method;
            }
              }
        }
Exemple #6
0
        private void Resolve(Emitter.Emitter emitter)
        {
            // already resolved?
              if (Kind != IdentifierKind.Unresolved) return;

              // atmark?
              if (AtmarkPrefix)
              {
            OwnerType = emitter.CurrentType.Name;

            var field = emitter.FindField(emitter.CurrentType.Name, Name);
            if (field != null)
              Kind = field.Static ? IdentifierKind.StaticField : IdentifierKind.Field;
            else
              Error(String.Format(Resources.errFieldNotFound, Name, emitter.CurrentType.Name));

            // additional check: dynamic field from static method
            if (emitter.CurrentMethod.Static && !field.Static)
              Error(String.Format(Resources.errDynamicFromStatic, field.Name));

            IdentifierType = field.Type.Signature;
              }

              // other prefix?
              else if (TypePrefix != null || ExpressionPrefix != null)
              {
            OwnerType = (TypePrefix != null ? TypePrefix.Data : ExpressionPrefix.GetExpressionType(emitter));

            // check class existence
            var type = emitter.FindType(OwnerType);
            if (type == null)
              Error(String.Format(Resources.errTypeNotFound, OwnerType), TypePrefix);

            // field ?
            var field = emitter.FindField(OwnerType, Name);
            Kind = (TypePrefix != null ? IdentifierKind.StaticField : IdentifierKind.Field);
            IdentifierType = field.Type.Signature;
              }

              else
              {
            // local variable
            if (emitter.CurrentMethod.Scope.Exists(Name))
            {
              Kind = IdentifierKind.Variable;
              IdentifierType = emitter.CurrentMethod.Scope.Find(Name).Type;
            }

            // parameter
            else if (emitter.CurrentMethod.Parameters.Contains(Name))
            {
              Kind = IdentifierKind.Parameter;
              IdentifierType = emitter.CurrentMethod.Parameters[Name].Type.Signature;
            }

            // no luck at all
            else
              Error(String.Format(Resources.errIdentifierUnresolved, Name));
              }
        }
Exemple #7
0
        ///////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            if (interpreter == null)
            {
                result = "invalid interpreter";
                return(ReturnCode.Error);
            }

            if (arguments == null)
            {
                result = "invalid argument list";
                return(ReturnCode.Error);
            }

            if (arguments.Count < 3)
            {
                result = WrongNumArgs;
                return(ReturnCode.Error);
            }

            ///////////////////////////////////////////////////////////////////

            OptionDictionary options = new OptionDictionary(new IOption[] {
                new Option(null, OptionFlags.None, Index.Invalid,
                           Index.Invalid, "-nodelete", null),
                new Option(null, OptionFlags.Unsafe, Index.Invalid,
                           Index.Invalid, "-hidden", null),
                new Option(typeof(IdentifierKind),
                           OptionFlags.MustHaveEnumValue | OptionFlags.Unsafe,
                           Index.Invalid, Index.Invalid, "-kind",
                           new Variant(IdentifierKind.None)),
                new Option(null, OptionFlags.MustHaveValue, Index.Invalid,
                           Index.Invalid, "-newnamevar", null),
                new Option(null, OptionFlags.None, Index.Invalid,
                           Index.Invalid, Option.EndOfOptions, null)
            });

            int argumentIndex = Index.Invalid;

            if (interpreter.GetOptions(
                    options, arguments, 0, 1, Index.Invalid, false,
                    ref argumentIndex, ref result) != ReturnCode.Ok)
            {
                return(ReturnCode.Error);
            }

            if ((argumentIndex == Index.Invalid) ||
                ((argumentIndex + 1) >= arguments.Count) ||
                ((argumentIndex + 2) < arguments.Count))
            {
                if ((argumentIndex != Index.Invalid) &&
                    Option.LooksLikeOption(arguments[argumentIndex]))
                {
                    result = OptionDictionary.BadOption(
                        options, arguments[argumentIndex]);
                }
                else
                {
                    result = WrongNumArgs;
                }

                return(ReturnCode.Error);
            }

            ///////////////////////////////////////////////////////////////////

            Variant        value = null;
            IdentifierKind kind  = IdentifierKind.None;

            if (options.IsPresent("-kind", ref value))
            {
                kind = (IdentifierKind)value.Value;
            }

            bool delete = true;

            if (options.IsPresent("-nodelete"))
            {
                delete = false;
            }

            bool hidden = false;

            if (options.IsPresent("-hidden"))
            {
                hidden = true;
            }

            string varName = null;

            if (options.IsPresent("-newnamevar", ref value))
            {
                varName = value.ToString();
            }

            ///////////////////////////////////////////////////////////////////

            string oldName     = arguments[argumentIndex];
            string newName     = arguments[argumentIndex + 1];
            Result localResult = null;

            if (interpreter.RenameAnyIExecute(
                    oldName, newName, varName, kind, false,
                    delete, hidden, ref localResult) == ReturnCode.Ok)
            {
                result = String.Empty;
                return(ReturnCode.Ok);
            }
            else
            {
                result = localResult;
                return(ReturnCode.Error);
            }
        }
 public static bool IsArgumentOrVar(IdentifierKind kind)
 {
     return(kind == IdentifierKind.Argument || kind == IdentifierKind.Var);
 }
 public void AddToSymbolTable(string name, IdentifierKind kind, string classType)
 {
     symbolTable.Add(name, kind, classType);
 }
 public static bool IsClassOrSubroutine(IdentifierKind kind)
 {
     return(kind == IdentifierKind.Class || kind == IdentifierKind.Subroutine);
 }
Exemple #11
0
        protected internal virtual async Task <string> CreateLdapFilterAsync(LdapConnection connection, string distinguishedName, IdentifierKind identifierKind, ClaimsPrincipal principal)
        {
            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }

            string ldapFilter;

            // ReSharper disable SwitchStatementHandlesSomeKnownEnumValuesWithDefault
            switch (identifierKind)
            {
            case IdentifierKind.SecurityIdentifier:
            {
                var securityIdentifierClaim = principal.Claims.FindFirst(ClaimTypes.PrimarySid, JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap[ClaimTypes.PrimarySid]);

                if (securityIdentifierClaim == null)
                {
                    throw new InvalidOperationException("Could not find a security-identifier-claim.");
                }

                ldapFilter = $"objectSid={securityIdentifierClaim.Value}";

                break;
            }

            case IdentifierKind.UserPrincipalName:
            {
                var userPrincipalNameClaim = principal.Claims.FindFirst(ClaimTypes.Upn, JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap[ClaimTypes.Upn]);

                if (userPrincipalNameClaim == null)
                {
                    throw new InvalidOperationException("Could not find a user-principal-name-claim.");
                }

                const string userPrincipalNameAttributeName = "userPrincipalName";

                ldapFilter = $"{userPrincipalNameAttributeName}={userPrincipalNameClaim.Value}";

                var emailClaim = principal.Claims.FindFirst(ClaimTypes.Email, JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap[ClaimTypes.Email]);

                if (emailClaim != null)
                {
                    ldapFilter = $"|({ldapFilter})({userPrincipalNameAttributeName}={emailClaim.Value})";
                }

                break;
            }

            default:
            {
                var nameClaim = principal.Claims.FindFirstNameClaim();

                if (nameClaim == null)
                {
                    throw new InvalidOperationException("Could not find a name-claim.");
                }

                if (connection == null)
                {
                    throw new ArgumentNullException(nameof(connection));
                }

                var nameParts = nameClaim.Value.Split('\\');
                var domain    = nameParts.FirstOrDefault();
                var domainControllerLdapFilter = await this.CreateDomainControllerLdapFilterAsync(domain).ConfigureAwait(false);

                // ReSharper disable PossibleNullReferenceException
                if (((SearchResponse)connection.SendRequest(new SearchRequest(distinguishedName, domainControllerLdapFilter, SearchScope.Base, "dc"))).Entries.Count == 0)
                {
                    throw new InvalidOperationException($"The name-claim \"{nameClaim.Value}\" has an invalid domain-part. The domain \"{domain}\" is invalid.");
                }
                // ReSharper restore PossibleNullReferenceException

                var samAccountName = nameParts.LastOrDefault();
                ldapFilter = $"sAMAccountName={samAccountName}";

                break;
            }
            }
            // ReSharper restore SwitchStatementHandlesSomeKnownEnumValuesWithDefault

            return(await Task.FromResult($"(&(objectClass=person)(objectClass=user)({ldapFilter}))").ConfigureAwait(false));
        }
Exemple #12
0
        protected internal virtual async Task <IDictionary <string, string> > GetAttributesInternalAsync(IEnumerable <string> attributes, IdentifierKind identifierKind, ClaimsPrincipal principal)
        {
            var domainName = await this.GetDomainNameAsync().ConfigureAwait(false);

            var distinguishedName = string.Join(',', domainName.Split('.').Select(part => $"dc={part}"));

            // ReSharper disable ConvertToUsingDeclaration
            using (var connection = await this.CreateConnectionAsync(domainName).ConfigureAwait(false))
            {
                var ldapFilter = await this.CreateLdapFilterAsync(connection, distinguishedName, identifierKind, principal).ConfigureAwait(false);

                return(await this.GetAttributesInternalAsync(attributes, connection, distinguishedName, ldapFilter, SearchScope.Subtree).ConfigureAwait(false));
            }
            // ReSharper restore ConvertToUsingDeclaration
        }
Exemple #13
0
        public virtual async Task <IDictionary <string, string> > GetAttributesAsync(IEnumerable <string> attributes, IdentifierKind identifierKind, ClaimsPrincipal principal)
        {
            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }

            try
            {
                if (this.Options.Value.ActiveDirectory.Impersonate)
                {
                    if (!(principal.Identity is WindowsIdentity windowsIdentity))
                    {
                        throw new InvalidOperationException("The identity is not a windows-identity.");
                    }

                    WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, () => this.GetAttributesInternalAsync(attributes, identifierKind, principal).Result);
                }

                return(await this.GetAttributesInternalAsync(attributes, identifierKind, principal).ConfigureAwait(false));
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException($"Could not get attributes for principal \"{principal.Identity?.Name}\".", exception);
            }
        }
 public IdentifierInfo(IdentifierKind kind)
 {
     Kind = kind;
     DeclaredTypeNames         = new string[0];
     DeclaredTypePropertyNames = new string[0];
 }
 public IdentifierInfo(IdentifierKind kind)
 {
     Kind = kind;
     DeclaredTypeNames = new string[0];
     DeclaredTypePropertyNames = new string[0];
 }
 public static bool IsFieldOrStatic(IdentifierKind kind)
 {
     return(kind == IdentifierKind.Field || kind == IdentifierKind.Static);
 }
Exemple #17
0
 public Identifier(string identifier, IdentifierKind kind, bool isDefinition, int?number = null) : base(NodeType.Identifier, identifier)
 {
     Kind         = kind;
     IsDefinition = isDefinition;
     Number       = number;
 }
Exemple #18
0
        ///////////////////////////////////////////////////////////////////////

        public void Free(
            bool global
            )
        {
            //
            // HACK: *SPECIAL CASE* We cannot dispose the global call frame
            //       unless we are [also] disposing of the interpreter itself.
            //
            if (global ||
                !FlagOps.HasFlags(flags, CallFrameFlags.NoFree, true))
            {
                kind        = IdentifierKind.None;
                id          = Guid.Empty;
                name        = null;
                group       = null;
                description = null;
                clientData  = null;
                frameId     = 0;
                frameLevel  = 0;
                flags       = CallFrameFlags.None;

                ///////////////////////////////////////////////////////////////

                if (tags != null)
                {
                    tags.Clear();
                    tags = null;
                }

                ///////////////////////////////////////////////////////////////

                index = 0;
                level = 0;

                ///////////////////////////////////////////////////////////////

                if (arguments != null)
                {
                    //
                    // BUGFIX: We can only mutate argument lists that we own.
                    //
                    if (ownArguments)
                    {
                        arguments.Clear();
                    }

                    arguments = null;
                }

                ///////////////////////////////////////////////////////////////

                ownArguments = false;

                ///////////////////////////////////////////////////////////////

                if (procedureArguments != null)
                {
                    procedureArguments.Clear();
                    procedureArguments = null;
                }

                ///////////////////////////////////////////////////////////////

                if (variables != null)
                {
                    variables.Clear();
                    variables = null;
                }

                ///////////////////////////////////////////////////////////////

                other    = null; /* NOTE: Not owned, do not dispose. */
                previous = null; /* NOTE: Not owned, do not dispose. */
                next     = null; /* NOTE: Not owned, do not dispose. */

                ///////////////////////////////////////////////////////////////

                engineData    = null; /* NOTE: Not owned, do not dispose. */
                auxiliaryData = null; /* NOTE: Not owned, do not dispose. */
                resolveData   = null; /* NOTE: Not owned, do not dispose. */
                extraData     = null; /* NOTE: Not owned, do not dispose. */
            }
        }