Ejemplo n.º 1
0
        override public void LeaveMethod(Method node)
        {
            InternalMethod derived = (InternalMethod)node.Entity;
            IMethod        super   = derived.Overriden;

            if (null != super)
            {
                TypeMemberModifiers derivedAccess = TypeSystemServices.GetAccess(derived);
                TypeMemberModifiers superAccess   = TypeSystemServices.GetAccess(super);
                if (derivedAccess < superAccess)
                {
                    Error(CompilerErrorFactory.DerivedMethodCannotReduceAccess(
                              node,
                              derived.FullName,
                              super.FullName,
                              derivedAccess,
                              superAccess));
                }
            }

            CheckUnusedLocals(node);
            CheckAbstractMethodCantHaveBody(node);
            CheckValidExtension(node);
        }
Ejemplo n.º 2
0
        public IAstAttribute CreateAstAttributeInstance()
        {
            object[] parameters = _attribute.Arguments.Count > 0 ? _attribute.Arguments.ToArray() : new object[0];

            IAstAttribute aa = null;

            try
            {
                aa = (IAstAttribute)Activator.CreateInstance(_type, parameters);
            }
            catch (MissingMethodException x)
            {
                _context.Errors.Add(CompilerErrorFactory.MissingConstructor(x, _attribute, _type, parameters));
                return(null);
            }

            aa.Attribute = _attribute;

            if (_attribute.NamedArguments.Count > 0)
            {
                bool initialized = true;

                foreach (ExpressionPair p in _attribute.NamedArguments)
                {
                    bool success = SetFieldOrProperty(aa, p);
                    initialized = initialized && success;
                }

                if (!initialized)
                {
                    return(null);
                }
            }

            return(aa);
        }
Ejemplo n.º 3
0
        private void ProcessMacro(Type actualType, MacroStatement node)
        {
            // HACK: workaround for mono
            if (-1 == Array.IndexOf(actualType.GetInterfaces(), typeof(IAstMacro)))
//			if (!typeof(IAstMacro).IsAssignableFrom(actualType))
            {
                Errors.Add(CompilerErrorFactory.InvalidMacro(node, actualType.FullName));
                return;
            }

            try
            {
                Statement replacement = ExpandMacro(actualType, node);
                if (null != node.Modifier)
                {
                    replacement = NormalizeStatementModifiers.CreateModifiedStatement(node.Modifier, replacement);
                }
                ReplaceCurrentNode(replacement);
            }
            catch (Exception error)
            {
                Errors.Add(CompilerErrorFactory.MacroExpansionError(node, error));
            }
        }
Ejemplo n.º 4
0
        void CheckBaseTypes(ClassDefinition node)
        {
            IType baseClass = null;

            foreach (TypeReference baseType in node.BaseTypes)
            {
                IType baseInfo = GetType(baseType);
                if (!baseInfo.IsInterface)
                {
                    if (null != baseClass)
                    {
                        Error(
                            CompilerErrorFactory.ClassAlreadyHasBaseType(baseType,
                                                                         node.Name,
                                                                         baseClass.FullName)
                            );
                    }
                    else
                    {
                        baseClass = baseInfo;
                        if (baseClass.IsFinal && !TypeSystemServices.IsError(baseClass))
                        {
                            Error(
                                CompilerErrorFactory.CannotExtendFinalType(
                                    baseType,
                                    baseClass.FullName));
                        }
                    }
                }
            }

            if (null == baseClass)
            {
                node.BaseTypes.Insert(0, CodeBuilder.CreateTypeReference(TypeSystemServices.ObjectType));
            }
        }
Ejemplo n.º 5
0
        override public void OnReferenceExpression(ReferenceExpression node)
        {
            IExternalEntity member = TypeSystemServices.GetOptionalEntity(node) as IExternalEntity;

            if (member == null)
            {
                return;
            }

            System.Attribute[] attributes = System.Attribute.GetCustomAttributes(member.MemberInfo, typeof(ObsoleteAttribute));
            foreach (ObsoleteAttribute attr in attributes)
            {
                if (attr.IsError)
                {
                    Errors.Add(
                        CompilerErrorFactory.Obsolete(node, member.ToString(), attr.Message));
                }
                else
                {
                    Warnings.Add(
                        CompilerWarningFactory.Obsolete(node, member.ToString(), attr.Message));
                }
            }
        }
Ejemplo n.º 6
0
 private void GenericParserError(LexicalInfo data, RecognitionException error)
 {
     _context.Errors.Add(CompilerErrorFactory.GenericParserError(data, error));
 }
Ejemplo n.º 7
0
        IType FindBestEnumeratorType()
        {
            //type is already an IEnumerator, use it
            if (IsAssignableFrom(TypeSystemServices.IEnumeratorType, CurrentEnumeratorType))
            {
                return(CurrentEnumeratorType);
            }

            IType bestEnumeratorType = null;

            _candidates.Clear();

            //resolution order:
            //1) type contains an applicable GetEnumerator() [whether or not type implements IEnumerator (as C# does)]
            CurrentEnumeratorType.Resolve(_candidates, "GetEnumerator", EntityType.Method);
            foreach (IEntity candidate in _candidates)
            {
                IMethod m = (IMethod)candidate;
                if (null != m.GenericInfo || 0 != m.GetParameters().Length || !m.IsPublic)
                {
                    continue;                     //only check public non-generic GetEnumerator with no argument
                }
                if (!IsAssignableFrom(TypeSystemServices.IEnumeratorGenericType, m.ReturnType) &&
                    !IsAssignableFrom(TypeSystemServices.IEnumeratorType, m.ReturnType))
                {
                    continue;                     //GetEnumerator does not return an IEnumerator or IEnumerator[of T]
                }
                bestEnumeratorType = m.ReturnType;
                _bestGetEnumerator = m;
                break;
            }

            //2) type explicitly implements IEnumerable[of T]
            if (null == bestEnumeratorType)
            {
                if (IsAssignableFrom(TypeSystemServices.IEnumerableGenericType, CurrentEnumeratorType))
                {
                    bestEnumeratorType = TypeSystemServices.IEnumeratorGenericType;
#if DNXCORE50
                    _bestGetEnumerator = TypeSystemServices.Map(Types.IEnumerableGeneric.GetTypeInfo().GetMethod("GetEnumerator"));
#else
                    _bestGetEnumerator = TypeSystemServices.Map(Types.IEnumerableGeneric.GetMethod("GetEnumerator"));
#endif
                }
            }

            //3) type explicitly implements IEnumerable
            if (null == bestEnumeratorType)
            {
                if (IsAssignableFrom(TypeSystemServices.IEnumerableType, CurrentEnumeratorType))
                {
                    bestEnumeratorType = TypeSystemServices.IEnumeratorType;
                    _bestGetEnumerator = TypeSystemServices.Map(Types.IEnumerable.GetMethod("GetEnumerator"));
                }
            }

            //4) error
            if (null == bestEnumeratorType)
            {
                Errors.Add(CompilerErrorFactory.InvalidIteratorType(_iteratorNode, CurrentEnumeratorType));
            }

            return(bestEnumeratorType);
        }
Ejemplo n.º 8
0
        public override void OnImport(Boo.Lang.Compiler.Ast.Import import)
        {
            INamespace oldns  = NameResolutionService.CurrentNamespace;
            IEntity    entity = null;

            try
            {
                NameResolutionService.EnterNamespace(NameResolutionService.CurrentNamespace.ParentNamespace);
                entity = NameResolutionService.ResolveQualifiedName(import.Namespace);
            }
            finally
            {
                NameResolutionService.EnterNamespace(oldns);
            }

            if (null == entity)
            {
                entity = NameResolutionService.ResolveQualifiedName(import.Namespace);
            }

            //if 'import X', try 'import X from X'
            //comment out next if block if this is not wanted
            if (null == entity && null == import.AssemblyReference)
            {
                if (TryAutoAddAssemblyReference(import))
                {
                    entity = NameResolutionService.ResolveQualifiedName(import.Namespace);
                }
            }

            if (null == entity)
            {
                Errors.Add(CompilerErrorFactory.InvalidNamespace(import));
                entity = TypeSystemServices.ErrorEntity;
            }
            else
            {
                if (!IsValidNamespace(entity))
                {
                    Errors.Add(CompilerErrorFactory.NotANamespace(import, entity.FullName));
                    entity = TypeSystemServices.ErrorEntity;
                }
                else
                {
                    string name = entity.FullName;
                    if (null != import.AssemblyReference)
                    {
                        NamespaceEntity nsInfo = entity as NamespaceEntity;
                        if (null != nsInfo)
                        {
                            entity = new AssemblyQualifiedNamespaceEntity(GetBoundAssembly(import.AssemblyReference), nsInfo);
                        }
                    }

                    if (null != import.Alias)
                    {
                        entity = new AliasedNamespace(import.Alias.Name, entity);
                        import.Alias.Entity = entity;
                        name = entity.Name;                         //use alias name instead of namespace name
                    }

                    //only add unique namespaces
                    Import cachedImport = nameSpaces[name] as Import;
                    if (cachedImport == null)
                    {
                        nameSpaces[name] = import;
                    }
                    else
                    {
                        //ignore for partial classes in separate files
                        if (cachedImport.LexicalInfo.FileName == import.LexicalInfo.FileName)
                        {
                            Warnings.Add(CompilerWarningFactory.DuplicateNamespace(
                                             import, import.Namespace));
                        }
                        RemoveCurrentNode();
                        return;
                    }
                }
            }

            _context.TraceInfo("{1}: import reference '{0}' bound to {2}.", import, import.LexicalInfo, entity.FullName);
            import.Entity = entity;
        }
Ejemplo n.º 9
0
        override public void OnAttribute(Ast.Attribute attribute)
        {
            if (null != attribute.Entity)
            {
                return;
            }

            var entity = NameResolutionService.ResolveQualifiedName(BuildAttributeName(attribute.Name, true))
                         ?? NameResolutionService.ResolveQualifiedName(BuildAttributeName(attribute.Name, false))
                         ?? NameResolutionService.ResolveQualifiedName(attribute.Name);

            if (entity == null)
            {
                var suggestion = NameResolutionService.GetMostSimilarTypeName(BuildAttributeName(attribute.Name, true))
                                 ?? NameResolutionService.GetMostSimilarTypeName(BuildAttributeName(attribute.Name, false));

                Error(attribute, CompilerErrorFactory.UnknownAttribute(attribute, attribute.Name, suggestion));
                return;
            }

            if (entity.IsAmbiguous())
            {
                Error(attribute, CompilerErrorFactory.AmbiguousReference(
                          attribute,
                          attribute.Name,
                          ((Ambiguous)entity).Entities));
                return;
            }

            if (EntityType.Type != entity.EntityType)
            {
                Error(attribute, CompilerErrorFactory.NameNotType(attribute, attribute.Name, entity, null));
                return;
            }

            IType attributeType = ((ITypedEntity)entity).Type;

            if (IsAstAttribute(attributeType))
            {
                ExternalType externalType = attributeType as ExternalType;
                if (null == externalType)
                {
                    Error(attribute, CompilerErrorFactory.AstAttributeMustBeExternal(attribute, attributeType));
                }
                else
                {
                    ScheduleAttributeApplication(attribute, externalType.ActualType);
                    RemoveCurrentNode();
                }
            }
            else
            {
                if (!IsSystemAttribute(attributeType))
                {
                    Error(attribute, CompilerErrorFactory.TypeNotAttribute(attribute, attributeType));
                }
                else
                {
                    // remember the attribute's type
                    attribute.Name   = attributeType.FullName;
                    attribute.Entity = entity;
                    CheckAttributeParameters(attribute);
                }
            }
        }
Ejemplo n.º 10
0
 public void GenericArgumentsCountMismatch(Node anchor, IType type)
 {
     CompilerErrors.Add(CompilerErrorFactory.GenericDefinitionArgumentCount(anchor, type.FullName, type.GenericInfo.GenericParameters.Length));
 }
Ejemplo n.º 11
0
        /// <summary>
        /// For the Namespace Prefix of the Node:
        /// - reports error if it is not defined
        /// - finds Namespace DOM object in the Module or ModuleMember and adds it to NsINFo of the current ModuleMember
        /// if the namespace is not added yet
        /// </summary>
        internal void ProcessNsPrefix(IMappedPair pair)
        {
            var nsPrefix = ((INsNode)pair).NsPrefix;

            if (string.IsNullOrEmpty(nsPrefix) ||
                nsPrefix.StartsWith("xml", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var ns = LookupNamespace(nsPrefix);

            if (ns == null)
            {
                _context.AddError(CompilerErrorFactory.NsPrefixNotDefined(pair.NameInterval, nsPrefix, _currentModule.FileName));
                return;
            }

            var foundNs = CurrentModuleMemberNsInfo.Namespaces.FirstOrDefault(n => n.Value == ns.Value);

            if (foundNs == null)
            {
                CurrentModuleMemberNsInfo.Namespaces.Add(ns);
            }
            else
            //If namespace is already defined with different prefix then changing prefix on pair
            if (foundNs.Name != nsPrefix)
            {
                ((INsNodeOverridable)pair).OverrideNsPrefix(foundNs.Name);
            }

            if (!(pair is DOM.Mapped.Attribute attribute) || attribute.Name != "type" || nsPrefix != "xsi")
            {
                return;
            }

            var typeInfo = attribute.Value?.Split(':');

            if (!(typeInfo?.Length > 1))
            {
                return;
            }

            nsPrefix = typeInfo[0];
            ns       = LookupNamespace(nsPrefix);
            if (ns == null)
            {
                _context.AddError(CompilerErrorFactory.NsPrefixNotDefined(pair.ValueInterval, nsPrefix, _currentModule.FileName));
                return;
            }
            foundNs = CurrentModuleMemberNsInfo.Namespaces.FirstOrDefault(n => n.Value == ns.Value);

            if (foundNs == null)
            {
                CurrentModuleMemberNsInfo.Namespaces.Add(ns);
            }
            else if (foundNs.Name != nsPrefix)
            {
                attribute.OverrideValue($"{foundNs.Name}:{typeInfo[1]}");
            }
        }
Ejemplo n.º 12
0
 public override void OnCustomStatement(CustomStatement node)
 {
     Error(CompilerErrorFactory.InvalidNode(node));
 }
Ejemplo n.º 13
0
 protected void AddCompilerError(LexicalInfo lexicalInfo, string msg)
 {
     Errors.Add(CompilerErrorFactory.CustomError(lexicalInfo, msg));
 }
Ejemplo n.º 14
0
        override public void OnAttribute(Boo.Lang.Compiler.Ast.Attribute attribute)
        {
            if (null != attribute.Entity)
            {
                return;
            }

            _elements.Clear();

            if (!NameResolutionService.ResolveQualifiedName(_elements, BuildAttributeName(attribute.Name)))
            {
                NameResolutionService.ResolveQualifiedName(_elements, attribute.Name);
            }

            if (_elements.Count > 0)
            {
                if (_elements.Count > 1)
                {
                    Error(attribute, CompilerErrorFactory.AmbiguousReference(
                              attribute,
                              attribute.Name,
                              _elements));
                }
                else
                {
                    IEntity tag = (IEntity)_elements[0];
                    if (EntityType.Type != tag.EntityType)
                    {
                        Error(attribute, CompilerErrorFactory.NameNotType(attribute, attribute.Name));
                    }
                    else
                    {
                        IType attributeType = ((ITypedEntity)tag).Type;
                        if (IsAstAttribute(attributeType))
                        {
                            ExternalType externalType = attributeType as ExternalType;
                            if (null == externalType)
                            {
                                Error(attribute, CompilerErrorFactory.AstAttributeMustBeExternal(attribute, attributeType.FullName));
                            }
                            else
                            {
                                ScheduleAttributeApplication(attribute, externalType.ActualType);

                                RemoveCurrentNode();
                            }
                        }
                        else
                        {
                            if (!IsSystemAttribute(attributeType))
                            {
                                Error(attribute, CompilerErrorFactory.TypeNotAttribute(attribute, attributeType.FullName));
                            }
                            else
                            {
                                // remember the attribute's type
                                attribute.Name   = attributeType.FullName;
                                attribute.Entity = attributeType;
                            }
                        }
                    }
                }
            }
            else
            {
                Error(attribute, CompilerErrorFactory.UnknownAttribute(attribute, attribute.Name));
            }
        }
Ejemplo n.º 15
0
        internal static RegexOptions GetRegexOptions(RELiteralExpression re)
        {
            RegexOptions ro = RegexOptions.None;

            if (String.IsNullOrEmpty(re.Options))
            {
                return(ro);
            }

            foreach (char opt in re.Options)
            {
                switch (opt)
                {
                /* common flags */
                case 'g':
                    break;                             //no-op on .NET, global by default

                case 'i':
                    ro |= RegexOptions.IgnoreCase;
                    break;

                case 'm':
                    ro |= RegexOptions.Multiline;
                    break;

                /* perl|python flags */
                case 's':
                    ro |= RegexOptions.Singleline;
                    break;

                case 'x':
                    //TODO: parser support, no-op for now
                    //ro |= RegexOptions.IgnorePatternWhitespace;
                    break;

                case 'l':                         //no-op on .NET, (l)ocale-aware by default
                    break;

                /* boo-specific flags */
                case 'n':                         //culture-(n)eutral
                    ro |= RegexOptions.CultureInvariant;
                    break;

                case 'c':
                                                #if !MONOTOUCH
                    ro |= RegexOptions.Compiled;
                                                #endif
                    break;

                case 'e':
                    ro |= RegexOptions.ExplicitCapture;
                    break;

                default:
                    My <CompilerErrorCollection> .Instance.Add(
                        CompilerErrorFactory.InvalidRegexOption(re, opt));

                    break;
                }
            }
            return(ro);
        }
Ejemplo n.º 16
0
 void MemberConflict(TypeMember member, string memberName)
 {
     Error(CompilerErrorFactory.MemberNameConflict(member, member.DeclaringType.FullName, memberName));
 }
Ejemplo n.º 17
0
 private static void GenericParserError(LexicalInfo sourceLocation, Exception x)
 {
     My <CompilerErrorCollection> .Instance.Add(CompilerErrorFactory.GenericParserError(sourceLocation, x));
 }
Ejemplo n.º 18
0
        private Block VisitAwaitExpression(AwaitExpression node, Expression resultPlace)
        {
            _seenAwait = true;
            var expression = Visit(node.BaseExpression);

            resultPlace = Visit(resultPlace);
            var getAwaiter = (IMethod)node["$GetAwaiter"];
            var getResult  = (IMethod)node["$GetResult"];

            if (getAwaiter == null)
            {
                var resolveList = new List <IEntity>();
                if (expression.ExpressionType.Resolve(resolveList, "GetAwaiter", EntityType.Method))
                {
                    getAwaiter = resolveList.Cast <IMethod>().First(m => m.GetParameters().Length == 0 && m.IsPublic);
                }
                else
                {
                    throw CompilerErrorFactory.MissingGetAwaiter(expression);
                }
                getResult = getAwaiter.ReturnType.GetMembers().OfType <IMethod>().Single(m => m.Name.Equals("GetResult"));
            }
            Debug.Assert(getAwaiter != null && getResult != null);
            var isCompletedProp = getAwaiter.ReturnType.GetMembers().OfType <IProperty>().SingleOrDefault(p => p.Name.Equals("IsCompleted"));

            if (isCompletedProp == null)
            {
                var resolveList = new List <IEntity>();
                if (getAwaiter.ReturnType.Resolve(resolveList, "IsCompleted", EntityType.Property))
                {
                    isCompletedProp = resolveList.Cast <IProperty>().First(p => p.GetParameters().Length == 0 && p.IsPublic);
                }
                if (isCompletedProp == null)
                {
                    throw new ArgumentException("No valid IsCompleted property found");
                }
            }
            var   isCompletedMethod = isCompletedProp.GetGetMethod();
            IType type;

            if (IsCustomTaskType(expression.ExpressionType))
            {
                type = getResult.ReturnType;
            }
            else
            {
                type = expression.ExpressionType.ConstructedInfo == null
                                ? TypeSystemServices.VoidType
                                : expression.ExpressionType.ConstructedInfo.GenericArguments[0];
            }

            // The awaiter temp facilitates EnC method remapping and thus have to be long-lived.
            // It transfers the awaiter objects from the old version of the MoveNext method to the new one.
            var awaiterType = getAwaiter.ReturnType;
            var awaiterTemp = CodeBuilder.DeclareTempLocal(_moveNext.Method, awaiterType);

            var getAwaiterInvocation = getAwaiter.IsExtension ?
                                       CodeBuilder.CreateMethodInvocation(getAwaiter, expression) :
                                       CodeBuilder.CreateMethodInvocation(expression, getAwaiter);
            var awaitIfIncomplete = new Block(
                // temp $awaiterTemp = <expr>.GetAwaiter();
                new ExpressionStatement(
                    CodeBuilder.CreateAssignment(
                        CodeBuilder.CreateLocalReference(awaiterTemp),
                        getAwaiterInvocation)),

                // if(!($awaiterTemp.IsCompleted)) { ... }
                new IfStatement(
                    new UnaryExpression(
                        UnaryOperatorType.LogicalNot,
                        GenerateGetIsCompleted(awaiterTemp, isCompletedMethod)),
                    GenerateAwaitForIncompleteTask(awaiterTemp),
                    null));

            TryStatementInfo currentTry = _tryStatementStack.Count > 0 ? _tryStatementStack.Peek() : null;

            if (currentTry != null)
            {
                ConvertTryStatement(currentTry);
            }

            var getResultCall = CodeBuilder.CreateMethodInvocation(
                CodeBuilder.CreateLocalReference(awaiterTemp),
                getResult);

            var nullAwaiter = CodeBuilder.CreateAssignment(
                CodeBuilder.CreateLocalReference(awaiterTemp),
                CodeBuilder.CreateDefaultInvocation(this.LexicalInfo, awaiterTemp.Type));

            if (resultPlace != null && type != TypeSystemServices.VoidType)
            {
                // $resultTemp = $awaiterTemp.GetResult();
                // $awaiterTemp = null;
                // $resultTemp
                InternalLocal resultTemp = CodeBuilder.DeclareTempLocal(_moveNext.Method, type);
                return(new Block(
                           awaitIfIncomplete,
                           new ExpressionStatement(
                               CodeBuilder.CreateAssignment(CodeBuilder.CreateLocalReference(resultTemp), getResultCall)),
                           new ExpressionStatement(nullAwaiter),
                           new ExpressionStatement(
                               CodeBuilder.CreateAssignment(resultPlace, CodeBuilder.CreateLocalReference(resultTemp)))));
            }

            // $awaiterTemp.GetResult();
            // $awaiterTemp = null;
            return(new Block(
                       awaitIfIncomplete,
                       new ExpressionStatement(getResultCall),
                       new ExpressionStatement(nullAwaiter)));
        }
Ejemplo n.º 19
0
        void ResolveAbstractMethod(ClassDefinition node,
                                   TypeReference baseTypeRef,
                                   IMethod entity)
        {
            if (entity.IsSpecialName)
            {
                return;
            }

            foreach (TypeMember member in node.Members)
            {
                if (entity.Name == member.Name &&
                    NodeType.Method == member.NodeType &&
                    IsCorrectExplicitMemberImplOrNoExplicitMemberAtAll(member, entity))
                {
                    Method method = (Method)member;
                    if (TypeSystemServices.CheckOverrideSignature(GetEntity(method), entity))
                    {
                        if (IsUnknown(method.ReturnType))
                        {
                            method.ReturnType = CodeBuilder.CreateTypeReference(entity.ReturnType);
                        }
                        else
                        {
                            if (entity.ReturnType != method.ReturnType.Entity)
                            {
                                Error(CompilerErrorFactory.ConflictWithInheritedMember(method, method.FullName, entity.FullName));
                            }
                        }

                        if (null != method.ExplicitInfo)
                        {
                            method.ExplicitInfo.Entity = entity;
                        }

                        if (!method.IsOverride && !method.IsVirtual)
                        {
                            method.Modifiers |= TypeMemberModifiers.Virtual;
                        }

                        _context.TraceInfo("{0}: Method {1} implements {2}", method.LexicalInfo, method, entity);
                        return;
                    }
                }
            }
            foreach (SimpleTypeReference parent in node.BaseTypes)
            {
                if (_classDefinitionList.Contains(parent.Name))
                {
                    depth++;
                    ResolveAbstractMethod(_classDefinitionList[parent.Name] as ClassDefinition, baseTypeRef, entity);
                    depth--;
                }
            }
            if (CheckInheritsInterfaceImplementation(node, entity))
            {
                return;
            }
            if (depth == 0)
            {
                if (!AbstractMemberNotImplemented(node, baseTypeRef, entity))
                {
                    //BEHAVIOR < 0.7.7: no stub, mark class as abstract
                    node.Members.Add(CodeBuilder.CreateAbstractMethod(baseTypeRef.LexicalInfo, entity));
                }
            }
        }
Ejemplo n.º 20
0
 private void MultipleAttributeUsageError(Attribute attribute, Type attrType)
 {
     Errors.Add(CompilerErrorFactory.MultipleAttributeUsage(attribute, attrType));
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Sets state of the current block and checks its integrity
        /// </summary>
        /// <param name="pair"></param>
        private void CheckBlockIntegrity(DOM.Pair pair)
        {
            if (_currentModule.TargetFormat == Module.TargetFormats.Xml)
            {
                return;
            }
            if (!_blockStateUnknown)
            {
                var blockState = _blockState.Peek();
                if (blockState == JsonGenerator.BlockStateEnum.Array)
                {
                    //Starting new block
                    if (string.IsNullOrEmpty(pair.Name) && pair.Assignment == AssignmentEnum.None)
                    {
                        _blockState.Push(((IMappedPair)pair).BlockType == BlockType.JsonArray
                            ? JsonGenerator.BlockStateEnum.Array
                            : JsonGenerator.BlockStateEnum.Object);
                    }

                    if (string.IsNullOrEmpty(pair.Name) || pair.Assignment == AssignmentEnum.None)
                    {
                        return;
                    }
                    ReportErrorForEachNodeInAliasContext(
                        n => CompilerErrorFactory.ArrayItemIsExpected(((IMappedPair)n).NameInterval, _currentModule.FileName));
                    Context.AddError(CompilerErrorFactory.ArrayItemIsExpected(((IMappedPair)pair).NameInterval, _currentModule.FileName));
                }
                else if (blockState == JsonGenerator.BlockStateEnum.Object)
                {
                    if (string.IsNullOrEmpty(pair.Name) && pair.Assignment == AssignmentEnum.None)
                    {
                        if (((IMappedPair)pair).BlockType == BlockType.JsonArray)
                        {
                            _blockState.Push(JsonGenerator.BlockStateEnum.Array);
                            ReportErrorForEachNodeInAliasContext(
                                n => CompilerErrorFactory.PropertyIsExpected(((IMappedPair)n).NameInterval, _currentModule.FileName));
                            Context.AddError(CompilerErrorFactory.PropertyIsExpected(((IMappedPair)pair).AssignmentInterval, _currentModule.FileName));
                        }
                        return;
                    }
                    if (!string.IsNullOrEmpty(pair.Name) && pair.Assignment != AssignmentEnum.None)
                    {
                        return;
                    }

                    //if(_currentModule.TargetFormat == Module.TargetFormats.Xml && ((IMappedPair)pair).IsValueNode ) return;

                    ReportErrorForEachNodeInAliasContext(
                        n => CompilerErrorFactory.PropertyIsExpected(((IMappedPair)n).NameInterval, _currentModule.FileName));
                    Context.AddError(CompilerErrorFactory.PropertyIsExpected(((IMappedPair)pair).NameInterval, _currentModule.FileName));
                }
                return;
            }

            if (string.IsNullOrEmpty(pair.Name) && pair.Assignment == AssignmentEnum.None)
            {
                _blockState.Push(((IMappedPair)pair).BlockType == BlockType.JsonArray
                    ? JsonGenerator.BlockStateEnum.Array
                    : JsonGenerator.BlockStateEnum.Object);
            }
            else
            {
                //This element is the first element of the block. It decides if the block is array or object
                _blockState.Push(string.IsNullOrEmpty(pair.Name) || pair.Assignment == AssignmentEnum.None
                    ? JsonGenerator.BlockStateEnum.Array
                    : JsonGenerator.BlockStateEnum.Object);
            }
            _blockStateUnknown = false;
        }
Ejemplo n.º 22
0
 private IEntity NameNotType(SimpleTypeReference node)
 {
     _context.Errors.Add(CompilerErrorFactory.NameNotType(node, node.ToCodeString()));
     return(TypeSystemServices.ErrorEntity);
 }
Ejemplo n.º 23
0
 private IEntity AmbiguousReference(SimpleTypeReference node, Ambiguous entity)
 {
     CompilerErrors().Add(CompilerErrorFactory.AmbiguousReference(node, node.Name, entity.Entities));
     return(TypeSystemServices.ErrorEntity);
 }
Ejemplo n.º 24
0
 private IEntity GenericArgumentsCountMismatch(TypeReference node, IType type)
 {
     _context.Errors.Add(CompilerErrorFactory.GenericDefinitionArgumentCount(node, type.FullName, type.GenericTypeDefinitionInfo.GenericParameters.Length));
     return(TypeSystemServices.ErrorEntity);
 }
Ejemplo n.º 25
0
 private static void InvalidNode(Node node)
 {
     throw CompilerErrorFactory.InvalidNode(node);
 }
Ejemplo n.º 26
0
        override public void OnMacroStatement(MacroStatement node)
        {
            Visit(node.Block);
            Visit(node.Arguments);

            Statement replacement = null;

            IEntity entity = NameResolutionService.ResolveQualifiedName(BuildMacroTypeName(node.Name));

            if (null == entity)
            {
                entity = NameResolutionService.ResolveQualifiedName(node.Name);
            }

            if (null == entity)
            {
                Errors.Add(CompilerErrorFactory.UnknownMacro(node, node.Name));
            }
            else
            {
                if (EntityType.Type != entity.EntityType)
                {
                    Errors.Add(CompilerErrorFactory.InvalidMacro(node, node.Name));
                }
                else
                {
                    IType        macroType = (IType)entity;
                    ExternalType type      = macroType as ExternalType;
                    if (null == type)
                    {
                        Errors.Add(CompilerErrorFactory.AstMacroMustBeExternal(node, macroType.FullName));
                    }
                    else
                    {
                        object macroInstance = Activator.CreateInstance(type.ActualType);
                        if (!(macroInstance is IAstMacro))
                        {
                            Errors.Add(CompilerErrorFactory.InvalidMacro(node, macroType.FullName));
                        }
                        else
                        {
                            try
                            {
                                using (IAstMacro macro = ((IAstMacro)macroInstance))
                                {
                                    macro.Initialize(_context);
                                    replacement = macro.Expand(node);
                                }
                            }
                            catch (Exception error)
                            {
                                Errors.Add(CompilerErrorFactory.MacroExpansionError(node, error));
                            }
                        }
                    }
                }
            }
            if (null != node.Modifier)
            {
                replacement = NormalizeStatementModifiers.CreateModifiedStatement(node.Modifier, replacement);
            }
            ReplaceCurrentNode(replacement);
        }
 protected void NotImplemented(Node node, string feature)
 {
     throw CompilerErrorFactory.NotImplemented(node, feature);
 }
Ejemplo n.º 28
0
 /// <inheritdoc />
 public void OnError(int code, Interval interval, params object[] args)
 {
     _context.AddError(CompilerErrorFactory.ParserError(Syntactik.ParsingErrors.Format(code, args), _fileName, interval.Begin.Line,
                                                        interval.Begin.Column));
 }
Ejemplo n.º 29
0
 void ParserError(LexicalInfo data, antlr.NoViableAltException error)
 {
     _context.Errors.Add(CompilerErrorFactory.UnexpectedToken(data, error, error.token.getText()));
 }
Ejemplo n.º 30
0
        private Expression Spill(
            BoundSpillSequenceBuilder builder,
            Expression expression,
            bool isRef           = false,
            bool sideEffectsOnly = false)
        {
            Debug.Assert(builder != null);

            while (true)
            {
                switch (expression.NodeType)
                {
                case NodeType.ListLiteralExpression:
                case NodeType.ArrayLiteralExpression:
                    Debug.Assert(!isRef);
                    Debug.Assert(!sideEffectsOnly);
                    var arrayInitialization = (ListLiteralExpression)expression;
                    var newInitializers     = VisitExpressionList(ref builder, arrayInitialization.Items, forceSpill: true);
                    arrayInitialization.Items = newInitializers;
                    return(arrayInitialization);

                case NodeType.HashLiteralExpression:
                    Debug.Assert(!isRef);
                    Debug.Assert(!sideEffectsOnly);
                    var hashInitialization  = (HashLiteralExpression)expression;
                    var newInitializerPairs = VisitExpressionPairList(ref builder, hashInitialization.Items, forceSpill: true);
                    hashInitialization.Items = newInitializerPairs;
                    return(hashInitialization);

                case SpillSequenceBuilder:
                    var sequenceBuilder = (BoundSpillSequenceBuilder)expression;
                    builder.Include(sequenceBuilder);
                    expression = sequenceBuilder.Value;
                    continue;

                case NodeType.SelfLiteralExpression:
                case NodeType.SuperLiteralExpression:
                    if (isRef || !expression.ExpressionType.IsValueType)
                    {
                        return(expression);
                    }
                    goto default;

                case NodeType.ParameterDeclaration:
                    if (isRef)
                    {
                        return(expression);
                    }
                    goto default;

                case NodeType.ReferenceExpression:
                    var local = expression.Entity as InternalLocal;
                    if (local != null)
                    {
                        if (local.Local["SynthesizedKind"] == AWAIT_SPILL_MARKER || isRef)
                        {
                            return(expression);
                        }
                    }
                    goto default;

                case NodeType.MemberReferenceExpression:
                    if (expression.Entity.EntityType == EntityType.Field)
                    {
                        var field = (IField)expression.Entity;
                        if (field.IsInitOnly)
                        {
                            if (field.IsStatic)
                            {
                                return(expression);
                            }
                            if (!field.DeclaringType.IsValueType)
                            {
                                // save the receiver; can get the field later.
                                var target = Spill(builder,
                                                   ((MemberReferenceExpression)expression).Target,
                                                   isRef && !field.Type.IsValueType,
                                                   sideEffectsOnly);
                                return(_F.CreateMemberReference(target, field));
                            }
                        }
                    }
                    goto default;

                case NodeType.MethodInvocationExpression:
                    var mie = (MethodInvocationExpression)expression;
                    if (expression.Entity == BuiltinFunction.Eval)
                    {
                        builder.AddExpressions(mie.Arguments.Where(a => a != mie.Arguments.Last));
                        expression = mie.Arguments.Last;
                        continue;
                    }
                    if (isRef)
                    {
                        Debug.Assert(mie.ExpressionType.IsPointer);
                        CompilerContext.Current.Errors.Add(CompilerErrorFactory.UnsafeReturnInAsync(mie));
                    }
                    goto default;

                case NodeType.BoolLiteralExpression:
                case NodeType.CharLiteralExpression:
                case NodeType.DoubleLiteralExpression:
                case NodeType.IntegerLiteralExpression:
                case NodeType.NullLiteralExpression:
                case NodeType.RELiteralExpression:
                case NodeType.StringLiteralExpression:
                case NodeType.TypeofExpression:
                    return(expression);

                default:
                    if (expression.ExpressionType == _tss.VoidType || sideEffectsOnly)
                    {
                        builder.AddStatement(new ExpressionStatement(expression));
                        return(null);
                    }
                    var replacement = _F.DeclareTempLocal(_currentMethod, expression.ExpressionType);

                    var assignToTemp = _F.CreateAssignment(
                        _F.CreateLocalReference(replacement),
                        expression);

                    builder.AddLocal(replacement);
                    builder.AddStatement(new ExpressionStatement(assignToTemp));
                    return(_F.CreateLocalReference(replacement));
                }
            }
        }