コード例 #1
0
        public IMyVisualBasicProvider GetMyProvider(IIntermediateCliManager identityManager)
        {
            switch (identityManager.RuntimeEnvironment.Version & ~CliFrameworkVersion.ClientProfile)
            {
            case CliFrameworkVersion.v1_0_3705:
                return(this.GetMyProvider(VisualBasicVersion.Version07, identityManager));

            case CliFrameworkVersion.v1_1_4322:
                return(this.GetMyProvider(VisualBasicVersion.Version08, identityManager));

            case CliFrameworkVersion.v2_0_50727:
            case CliFrameworkVersion.v3_0:
            case CliFrameworkVersion.v3_5:
                return(this.GetMyProvider(VisualBasicVersion.Version09, identityManager));

            case CliFrameworkVersion.v4_0_30319:
                return(this.GetMyProvider(VisualBasicVersion.Version10, identityManager));

            case CliFrameworkVersion.v4_5:
                return(this.GetMyProvider(VisualBasicVersion.Version11, identityManager));

            case CliFrameworkVersion.v4_6:
                return(this.GetMyProvider(VisualBasicVersion.Version12, identityManager));

            default:
                return(this.GetMyProvider(VisualBasicVersion.CurrentVersion, identityManager));
            }
        }
コード例 #2
0
 public void Build(ParserCompiler compiler, ParserBuilder parserBuilder, IIntermediateCliManager identityManager)
 {
     /* *
      * After much of the static analysis has been completed on the grammar, it's now time to generate the parser's full state transition detail.
      * */
     BuildGetValidSyntaxCore(compiler, parserBuilder, identityManager);
 }
コード例 #3
0
        public Tuple <IIntermediateInterfaceType, IIntermediateClassType> Build(Tuple <ParserCompiler, CommonSymbolBuilder, IIntermediateAssembly, GenericSymbolStreamBuilder> input)
        {
            this.assembly           = input.Item3;
            this.compiler           = input.Item1;
            this.tokenSymbolBuilder = input.Item2;
            this._identityManager   = (IIntermediateCliManager)this.assembly.IdentityManager;


            var resultInterface = assembly.DefaultNamespace.Parts.Add().Interfaces.Add("I{0}SymbolStream", this.compiler.Source.Options.AssemblyName);
            var resultClass     = assembly.DefaultNamespace.Parts.Add().Classes.Add("{0}SymbolStream", this.compiler.Source.Options.AssemblyName);

            resultClass.BaseType = input.Item4.ResultClass.MakeGenericClosure(tokenSymbolBuilder.ILanguageSymbol);
            resultClass.ImplementedInterfaces.ImplementInterfaceQuick(resultInterface);
            resultInterface.ImplementedInterfaces.Add(input.Item4.ResultInterface.MakeGenericClosure(tokenSymbolBuilder.ILanguageSymbol));
            this.ResultInterface             = resultInterface;
            this.ResultClass                 = resultClass;
            this.ResultInterface.AccessLevel = AccessLevelModifiers.Public;
            this.ResultClass.AccessLevel     = AccessLevelModifiers.Internal;

            //Interface
            this.CreateReduce();

            //Class
            return(Tuple.Create(this.ResultInterface, this.ResultClass));
        }
コード例 #4
0
        public IIntermediateInterfaceType Build(Tuple <ParserCompiler, CommonSymbolBuilder, IIntermediateAssembly> input)
        {
            this.compiler         = input.Item1;
            this.rootSymbol       = input.Item2;
            this.assembly         = input.Item3;
            this._identityManager = (IIntermediateCliManager)this.assembly.IdentityManager;
            INamespaceDeclaration targetSpace;
            var targetSpaceName = TypeSystemIdentifiers.GetDeclarationIdentifier(string.Format("{0}.Cst", this.assembly.DefaultNamespace.FullName));

            if (!assembly.Namespaces.PathExists(targetSpaceName.Name))
            {
                targetSpace = this.assembly.DefaultNamespace.Namespaces.Add("Cst");
            }
            else
            {
                targetSpace = this.assembly.DefaultNamespace.Namespaces[targetSpaceName];
            }
            var mutableTargetSpace = (IIntermediateNamespaceDeclaration)targetSpace;

            this.resultInterface = mutableTargetSpace.Parts.Add().Interfaces.Add("I{0}Token", compiler.Source.Options.AssemblyName);
            this.resultInterface.ImplementedInterfaces.Add(this.rootSymbol.ILanguageSymbol);
            this.resultInterface.AccessLevel = AccessLevelModifiers.Public;
            this.BuildStartPosition();
            this.BuildEndPosition();
            this.BuildStartTokenIndex();
            return(this.resultInterface);
        }
コード例 #5
0
        /// <summary>
        /// Handles construction of the elements yielded by the
        /// <see cref="ParserBuilder"/> with the <paramref name="input"/>
        /// provided.
        /// </summary>
        /// <param name="input">The <see cref="Tuple{T1, T2, T3}"/> which provides the
        /// <see cref="ParserCompiler"/>, <see cref="TokenSymbolBuilder"/> and
        /// <see cref="IIntermediateAssembly"/> necessary to perform the operation.</param>
        /// <returns>A <see cref="Tuple{T1, T2, T3}"/> which yields the
        /// <see cref="IIntermediateInterfaceType"/>, <see cref="IIntermediateClassType"/>
        /// for the result parser of the language, and
        /// <see cref="LexerBuilder"/> of the language which denotes the class
        /// and interface of the tokenizer.</returns>
        public Tuple <IIntermediateInterfaceType, IIntermediateClassType, LexerBuilder> Build(Tuple <ParserCompiler, TokenSymbolBuilder, IIntermediateAssembly, RegularLanguageDFAState> input)
        {
            this.compiler            = input.Item1;
            this._tokenSymbolBuilder = input.Item2;
            this._assembly           = input.Item3;
            this._identityManager    = (IIntermediateCliManager)this._assembly.IdentityManager;
            this._parserInterface    = _assembly.DefaultNamespace.Parts.Add().Interfaces.Add("I{0}", compiler.Source.Options.ParserName);
            this._parserClass        = _assembly.DefaultNamespace.Parts.Add().Classes.Add(compiler.Source.Options.ParserName);
            this._parserClass.Assembly.ScopeCoercions.Add("System.Linq");

            this._genericSymbolStreamBuilder = new GenericSymbolStreamBuilder();
            this._symbolStreamBuilder        = new SymbolStreamBuilder();
            this._lexerBuilder                = new LexerBuilder();
            this._parserClass.AccessLevel     = AccessLevelModifiers.Internal;
            this._parserInterface.AccessLevel = AccessLevelModifiers.Public;
            this._lexerCore                                 = input.Item4;
            this._parserState                               = this._parserClass.Fields.Add(new TypedName("_state", _assembly.IdentityManager.ObtainTypeReference(RuntimeCoreType.Int32)));
            this._parserState.AccessLevel                   = AccessLevelModifiers.Private;
            this._parserStateProp                           = this._parserInterface.Properties.Add(new TypedName("State", this._parserState.FieldType), true, false);
            this._parserStatePropImpl                       = this._parserClass.Properties.Add(new TypedName("State", this._parserState.FieldType), true, true);
            this._parserStatePropImpl.AccessLevel           = AccessLevelModifiers.Public;
            this._parserStatePropImpl.SetMethod.AccessLevel = AccessLevelModifiers.Private;
            this._parserStatePropImpl.GetMethod.Return(this._parserState.GetReference());
            this._parserStatePropImpl.SetMethod.Assign(this._parserState.GetReference(), this._parserStatePropImpl.SetMethod.ValueParameter.GetReference());
            this._parserClass.ImplementedInterfaces.ImplementInterfaceQuick(this._parserInterface);
            return(Tuple.Create(this.ParserInterface, this.ParserClass, this._lexerBuilder));
        }
コード例 #6
0
 public void Build(ParserCompiler compiler, IIntermediateAssembly assembly)
 {
     this._compiler        = compiler;
     this._assembly        = assembly;
     this._identityManager = ((IIntermediateCliManager)(this._assembly.IdentityManager));
     this.BuildFixedTokenClass();
 }
コード例 #7
0
 public void Build(ParserCompiler compiler, IIntermediateAssembly assembly)
 {
     this._compiler        = compiler;
     this._assembly        = assembly;
     this._identityManager = ((IIntermediateCliManager)(assembly.IdentityManager));
     CreateICharStreamSegment(assembly);
     CreateCharStreamSegment(assembly);
 }
コード例 #8
0
 public void Build2(ParserCompiler compiler, ParserBuilder parserBuilder, IIntermediateCliManager identityManager)
 {
     BuildCullAmbiguitiesCore(compiler, parserBuilder, identityManager);
     BuildGetValidSyntax(compiler, parserBuilder, identityManager);
     BuildDebuggerDisplayForSymbols(compiler, parserBuilder, identityManager);
     BuildVisitorModel(compiler, identityManager);
     BuildCullAmbiguities(compiler, parserBuilder, identityManager);
 }
コード例 #9
0
        private void BuildVisitorModel(ParserCompiler compiler, IIntermediateCliManager identityManager)
        {
            var returnType             = identityManager.ObtainTypeReference(RuntimeCoreType.VoidType);
            var visitorInterface       = compiler.RuleSymbolBuilder.ILanguageRuleSymbol.Assembly.DefaultNamespace.Parts.Add().Interfaces.Add("I{0}Visitor", compiler.Source.Options.AssemblyName);
            var visitorResultInterface = compiler.RuleSymbolBuilder.ILanguageRuleSymbol.Assembly.DefaultNamespace.Parts.Add().Interfaces.Add("I{0}ReturnVisitor", compiler.Source.Options.AssemblyName);
            var tParamResult           = visitorResultInterface.TypeParameters.Add("TResult");

            BuildVisitor(compiler, returnType, visitorInterface, identityManager);
            BuildVisitor(compiler, tParamResult, visitorResultInterface, identityManager);
        }
コード例 #10
0
        /// <summary>
        /// Creates a new <see cref="IIntermediateAssembly"/> with the <paramref name="name"/> and
        /// <paramref name="version"/> provided.
        /// </summary>
        /// <param name="name">The <see cref="String"/> value representing part of the identity of the assembly.</param>
        /// <param name="identityManager">The <see cref="IIntermediateCliManager"/> which is used to marshal type identities
        /// in the current type model.</param>
        /// <param name="version">The <see cref="CSharpLanguageVersion"/> to which the <see cref="ICSharpAssembly"/>
        /// is built against.</param>
        /// <returns>A new <see cref="ICSharpAssembly"/>
        /// with the <paramref name="name"/> and <paramref name="version"/> provided.</returns>
        /// <exception cref="System.ArgumentNullException">thrown when <paramref name="name"/> is null.</exception>
        /// <exception cref="System.ArgumentException">thrown when <paramref name="name"/> is <see cref="String.Empty"/>
        /// or <paramref name="version"/> is not one of <see cref="CSharpLanguageVersion"/>.</exception>
        public ICSharpAssembly CreateAssembly(string name, IIntermediateCliManager identityManager, CSharpLanguageVersion version)
        {
            var provider = this.GetProvider(version);
            IIntermediateAssemblyCtorLanguageService <ICSharpProvider, ICSharpLanguage, ICSharpAssembly> creatorService;

            if (provider.TryGetService <IIntermediateAssemblyCtorLanguageService <ICSharpProvider, ICSharpLanguage, ICSharpAssembly> >(LanguageGuids.Services.IntermediateAssemblyCreatorService, out creatorService))
            {
                return(creatorService.New(name));
            }
            var resultAssembly = new CSharpAssembly(name, provider, provider.IdentityManager.RuntimeEnvironment);

            provider.IdentityManager.AssemblyCreated(resultAssembly);
            return(resultAssembly);
        }
コード例 #11
0
        private void BuildCullAmbiguitiesCore(ParserCompiler compiler, ParserBuilder parserBuilder, IIntermediateCliManager identityManager)
        {
            bool lexicallyAmbiguousModel = compiler._GrammarSymbols.AmbiguousSymbols.Count() > 0;

            if (!lexicallyAmbiguousModel)
            {
                return;
            }
            this._cullAmbiguities = this._getValidSyntaxMethodInternalImpl
                                    .Parent
                                    .Methods
                                    .Add(
                new TypedName("CullAmbiguitiesFrom", compiler.LexicalSymbolModel.ValidSymbols),
                new TypedNameSeries(
                    new TypedName("unambiguousSource", compiler.LexicalSymbolModel.ValidSymbols)));
            var allAmbiguities = compiler.LexicalSymbolModel.GenerateSymbolstoreVariation(new GrammarVocabulary(compiler.GrammarSymbols, compiler._GrammarSymbols.AmbiguousSymbols.ToArray()), "AllAmbiguities", string.Format("Returns a @s:{0}; value that represents all ambiguous identities.", compiler.LexicalSymbolModel.ValidSymbols.Name));

            allAmbiguities.Name          = "AllAmbiguities";
            this._AllAmbiguitiesField    = allAmbiguities;
            _cullAmbiguities.AccessLevel = AccessLevelModifiers.Public;
        }
コード例 #12
0
        public static IEnumerable <IVisitorImplementationBuilder> GetImplementationContext(IAssembly assembly, ICSharpAssembly resultAssembly, IIntermediateCliManager identityManager)
        {
            var attributeContext        = new VisitorModelCommonTypeContext(identityManager);
            var visitorBuilders         = GetVisitorContexts(assembly, attributeContext, resultAssembly, identityManager);
            var distinctImplementations = new HashSet <VisitorImplementationTargetDetail>(
                from metadatum in assembly.Metadata.Where(k => k.Type == attributeContext.ImplementationTargetAttribute)
                select VisitorImplementationTargetDetail.DeriveFromMetadata(metadatum));
            var inheritanceDetails =
                new HashSet <VisitorImplementationInheritanceDetail>(
                    assembly
                    .Metadata
                    .Where(k => k.Type == attributeContext.ImplementationInheritanceAttribute)
                    .Select(k => VisitorImplementationInheritanceDetail.DeriveFromMetadata(k)));
            var implementationDetail =
                (from inheritanceDetail in inheritanceDetails
                 orderby inheritanceDetail.TargetContext,
                 inheritanceDetail.VisitRefactorName,
                 inheritanceDetail.VisitRefactorAbstract,
                 inheritanceDetail.ContextualVisitor,
                 inheritanceDetail.YieldingVisitor
                 join implementation in distinctImplementations on inheritanceDetail.ImplementationDetailMatch equals implementation
                 group inheritanceDetail by implementation).ToDictionary(k => k.Key, v => v.ToArray());

            foreach (var detail in implementationDetail.Keys)
            {
                detail.InheritanceDetail = new ControlledCollection <VisitorImplementationInheritanceDetail>(implementationDetail[detail]);
            }
            var implementationBuilders =
                (from implementation in implementationDetail.Keys
                 let visitorBuilderQuery =
                     from inheritanceDetail in implementationDetail[implementation]
                     from visitorDetail in inheritanceDetail.VisitorTargets
                     join visitor in visitorBuilders on new { visitorDetail.TargetContext, visitorDetail.ContextualVisitor, visitorDetail.YieldingVisitor } equals new { visitor.Detail.TargetContext, visitor.Detail.ContextualVisitor, visitor.Detail.YieldingVisitor }
                 group visitor by GetInheritanceDetailKey(inheritanceDetail)
                 select GetImplementationBuilder(resultAssembly, attributeContext, implementation, visitorBuilderQuery, assembly))
                .ToArray();

            foreach (var builder in implementationBuilders)
            {
                yield return(builder);
            }
        }
コード例 #13
0
        private void BuildCullAmbiguities(ParserCompiler compiler, ParserBuilder parserBuilder, IIntermediateCliManager identityManager)
        {
            bool lexicallyAmbiguousModel = compiler._GrammarSymbols.AmbiguousSymbols.Count() > 0;

            if (!lexicallyAmbiguousModel)
            {
                return;
            }
            var runningAmbiguities = this._cullAmbiguities.Locals.Add(
                new TypedName("runningAmbiguities", compiler.LexicalSymbolModel.ValidSymbols), new DefaultValueExpression(compiler.LexicalSymbolModel.ValidSymbols));
            var resultAmbiguities = this._cullAmbiguities.Locals.Add(
                new TypedName("resultAmbiguities", compiler.LexicalSymbolModel.ValidSymbols), new DefaultValueExpression(compiler.LexicalSymbolModel.ValidSymbols));
            var unambiguousSource = this._cullAmbiguities.Parameters["unambiguousSource"];

            this._cullAmbiguities.Comment("Remove the ambiguities that are currently present, a larger multiple-symbol ambiguity may trump what was there due to the follow-union.");
            this._cullAmbiguities.Assign((IMemberReferenceExpression)unambiguousSource.GetReference(), AssignmentOperation.BitwiseExclusiveOrAssign, unambiguousSource.GetReference().BitwiseAnd(_AllAmbiguitiesField.GetReference()));
            bool first = true;

            foreach (var ambiguity in compiler._GrammarSymbols.AmbiguousSymbols)
            {
                var ambiguityDetail          = compiler.AmbiguityDetail[ambiguity];
                IBlockStatementParent target = this._cullAmbiguities;
                if (first)
                {
                    first = false;
                }
                else
                {
                    target = target.If(runningAmbiguities.GetReference().BitwiseAnd(ambiguityDetail.AmbiguityKeyReference.GetReference()).InequalTo(ambiguityDetail.AmbiguityKeyReference.GetReference()));
                }
                var assignmentCheck = target.If(unambiguousSource.BitwiseAnd(ambiguityDetail.AmbiguityKeyReference).EqualTo(ambiguityDetail.AmbiguityKeyReference));
                assignmentCheck.Assign(runningAmbiguities.GetReference(), AssignmentOperation.BitwiseOrAssign, ambiguityDetail.AmbiguityKeyReference.GetReference());
                assignmentCheck.Assign(resultAmbiguities.GetReference(), AssignmentOperation.BitwiseOrAssign, ambiguityDetail.AmbiguityReference.GetReference());
            }
            _cullAmbiguities.Return(resultAmbiguities.GetReference());
        }
コード例 #14
0
 public ErrorContextBuilder(ParserCompiler compiler, IIntermediateCliManager identityManager, IIntermediateAssembly assembly)
 {
     this._identityManager = identityManager;
     this._assembly        = assembly;
     this._compiler        = compiler;
 }
コード例 #15
0
        private void BuildGetValidSyntax(ParserCompiler compiler, ParserBuilder parserBuilder, IIntermediateCliManager identityManager)
        {
            bool lexicallyAmbiguousModel = compiler._GrammarSymbols.AmbiguousSymbols.Count() > 0;
            var  advanceAdapters         =
                compiler
                .AdvanceMachines.Values
                .Select(k => k.All)
                .DefaultIfEmpty().Aggregate(
                    (a, b) =>
                    a.Concat(b));

            if (advanceAdapters == null)
            {
                advanceAdapters = new PredictionTreeDFAdapter[0];
            }
            var adapters              = compiler.FollowAdapters.Select(k => k.Value.AssociatedState).Concat(compiler.AllRuleAdapters.Select(k => k.Value.AssociatedState)).Concat(advanceAdapters.DefaultIfEmpty().Where(k => k != null).Select(k => k.AssociatedState)).Distinct().OrderBy(k => k.StateValue).ToArray();
            var distinctStateValues   = adapters.Select(k => k.StateValue).Distinct().ToArray();
            var stateSymbolStoreEntry =
                (from state in adapters
                 /* Since the other adapters are state-machines derived from the projection of a given state of a rule, normal adapters (derived from non-expanded lookahead) must be aggregated */
                 join normalAdapter in compiler.AllRuleAdapters on state equals normalAdapter.Value.AssociatedState into normalVariantSet
                 from normalAdapter in normalVariantSet.DefaultIfEmpty()
                 let fc = (normalAdapter.Value == null || normalAdapter.Value.OutgoingTransitions.Count == 0 || normalAdapter.Value.AssociatedContext.Leaf.LookAhead.Count == 0) ? state.OutTransitions.FullCheck : normalAdapter.Value.AssociatedContext.Leaf.LookAhead.Keys.Aggregate(GrammarVocabulary.UnionAggregateDelegate)
                          group new { State = state, Grammar = fc, GrammarStore = compiler.LexicalSymbolModel.GenerateSymbolstoreVariation(fc) } by new { Grammar = fc, IsEdge = state.IsEdge }).ToDictionary(k => k.Key, v => v.ToArray());
            var stateParam  = _getValidSyntaxMethodInternalImpl.Parameters["state"];
            var ruleContext = _getValidSyntaxMethodInternalImpl.Parameters["ruleContext"];
            var initialPass = _getValidSyntaxMethodInternalImpl.Parameters["initialPass"];

            if (!lexicallyAmbiguousModel)
            {
                _getValidSyntaxMethodInternalImpl.Parameters.Remove(initialPass);
                initialPass = null;
            }

            _getValidSyntaxMethodImpl.AccessLevel = AccessLevelModifiers.Public;

            var getSyntaxMethodImplInvocation = _getValidSyntaxMethodInternalImpl.GetReference().Invoke(parserBuilder._StateImpl.GetReference(), parserBuilder._CurrentContextImpl.GetReference());

            _getValidSyntaxMethodImpl.Return(getSyntaxMethodImplInvocation);
            if (lexicallyAmbiguousModel)
            {
                getSyntaxMethodImplInvocation.Arguments.Add(IntermediateGateway.TrueValue);
            }
            ITypedLocalMember pushAmbiguityContext = null;

            if (lexicallyAmbiguousModel)
            {
                pushAmbiguityContext = _getValidSyntaxMethodInternalImpl.Locals.Add(
                    new TypedName("pushAmbiguityContext", RuntimeCoreType.Boolean, identityManager),
                    IntermediateGateway.FalseValue);
            }

            ITypedLocalMember validResult = null;

            if (lexicallyAmbiguousModel)
            {
                validResult = _getValidSyntaxMethodInternalImpl.Locals.Add(
                    new TypedName("result", compiler.LexicalSymbolModel.ValidSymbols),
                    this._getValidSyntaxMethodInternalImpl.ReturnType.GetNewExpression());
            }

            var switchStatement = this._getValidSyntaxMethodInternalImpl.Switch(stateParam.GetReference());

            foreach (var uniqueGrammarSet in stateSymbolStoreEntry.Keys)
            {
                var           currentSet   = stateSymbolStoreEntry[uniqueGrammarSet];
                IExpression[] stateIndices = new IExpression[currentSet.Length];
                currentSet = currentSet.OrderBy(k => k.State.StateValue).ToArray();
                for (int stateIndex = 0; stateIndex < currentSet.Length; stateIndex++)
                {
                    stateIndices[stateIndex] = currentSet[stateIndex].State.StateValue.ToPrimitive();
                }

                var currentCase = switchStatement.Case(stateIndices);
                currentCase.Comment(currentSet[0].Grammar.ToString());
                if (uniqueGrammarSet.IsEdge)
                {
                    //Inject logic to look up in the stack.
                    if (lexicallyAmbiguousModel)
                    {
                        var nullCheck = currentCase.If(ruleContext.InequalTo(IntermediateGateway.NullValue));
                        nullCheck.Assign(validResult.GetReference(), currentSet[0].GrammarStore.GetReference().BitwiseOr(_getValidSyntaxMethodInternalImpl.GetReference().Invoke(compiler.RuleSymbolBuilder.FollowState.GetReference(ruleContext.GetReference()), compiler.RuleSymbolBuilder.Parent.GetReference(ruleContext.GetReference()), IntermediateGateway.FalseValue)));
                        nullCheck.If(initialPass.GetReference())
                        .Assign(pushAmbiguityContext.GetReference(), IntermediateGateway.TrueValue);
                        nullCheck.CreateNext();
                        nullCheck.Next.Assign(validResult.GetReference(), currentSet[0].GrammarStore.GetReference());
                    }
                    else
                    {
                        var nullCheck = currentCase.If(ruleContext.InequalTo(IntermediateGateway.NullValue));
                        nullCheck.Return(currentSet[0].GrammarStore.GetReference().BitwiseOr(_getValidSyntaxMethodInternalImpl.GetReference().Invoke(compiler.RuleSymbolBuilder.FollowState.GetReference(ruleContext.GetReference()), compiler.RuleSymbolBuilder.Parent.GetReference(ruleContext.GetReference()))));
                        nullCheck.CreateNext();
                        nullCheck.Next.Return(currentSet[0].GrammarStore.GetReference());
                    }
                }
                else if (lexicallyAmbiguousModel)
                {
                    currentCase.Assign(validResult.GetReference(), currentSet[0].GrammarStore.GetReference());
                }
                else
                {
                    currentCase.Return(currentSet[0].GrammarStore.GetReference());
                }
            }
            if (lexicallyAmbiguousModel)
            {
                this._getValidSyntaxMethodInternalImpl.If(pushAmbiguityContext.GetReference())
                .Assign(validResult.GetReference(), AssignmentOperation.BitwiseOrAssign,
                        _cullAmbiguities.GetReference().Invoke(validResult.GetReference()));
            }
            if (lexicallyAmbiguousModel)
            {
                this._getValidSyntaxMethodInternalImpl.Return(validResult.GetReference());
            }
            else
            {
                this._getValidSyntaxMethodInternalImpl.Return(this._getValidSyntaxMethodInternalImpl.ReturnType.GetNewExpression());
            }
            this._getValidSyntaxMethodInternalImpl.AccessLevel = AccessLevelModifiers.Private;
        }
コード例 #16
0
 private static ICSharpAssembly CreateAssembly(string assemName, IIntermediateCliManager identityManager)
 {
     IntermediateCliGateway.AddGlobalResolutionPath(Path.GetDirectoryName(typeof(Program).Assembly.Location));
     return(LanguageVendors.Microsoft.GetCSharpLanguage().GetProvider(CSharpLanguageVersion.Version5, identityManager).CreateAssembly(assemName));
 }
コード例 #17
0
        public static CharStreamClass CreateBitStream(IIntermediateTypeParent parent, IIntermediateCliManager identityManager)
        {
            IIntermediateClassType result = parent.Classes.Add("CharStream");

            result.AccessLevel = AccessLevelModifiers.Internal;
            IIntermediateClassFieldMember charBuffer = result.Fields.Add(new TypedName("buffer", identityManager.ObtainTypeReference(RuntimeCoreType.Char).MakeArray()));

            charBuffer.AccessLevel = AccessLevelModifiers.Internal;
            IIntermediateClassFieldMember charBufferSize = result.Fields.Add(new TypedName("actualSize", identityManager.ObtainTypeReference(RuntimeCoreType.Int32)));

            charBufferSize.AccessLevel = AccessLevelModifiers.Internal;
            charBufferSize.InitializationExpression = IntermediateGateway.NumberZero;
            var purgeMethod      = AddPurgeMethod(result, charBufferSize, identityManager);
            var growBufferMethod = AddGrowBufferMethod(result, charBufferSize, charBuffer, identityManager);
            var pushStringMethod = AddPushStringMethod(result, charBufferSize, charBuffer, growBufferMethod, identityManager);
            var toStringMethod   = AddToStringMethod(result, charBufferSize, charBuffer, identityManager);
            var pushCharMethod   = AddPushMethod(result, charBufferSize, charBuffer, growBufferMethod, identityManager);

            return(new CharStreamClass(result, charBuffer, charBufferSize, purgeMethod, pushStringMethod, pushCharMethod, toStringMethod, growBufferMethod));
        }
コード例 #18
0
        private static IIntermediateClassMethodMember AddPurgeMethod(IIntermediateClassType result, IIntermediateClassFieldMember charBufferSize, IIntermediateCliManager identityManager)
        {
            var purgeMethod = result.Methods.Add(new TypedName("Purge", identityManager.ObtainTypeReference(RuntimeCoreType.VoidType)));

            purgeMethod.AccessLevel = AccessLevelModifiers.Public;
            purgeMethod.Assign(charBufferSize.GetReference(), IntermediateGateway.NumberZero);
            return(purgeMethod);
        }
コード例 #19
0
        private static IIntermediateClassMethodMember AddGrowBufferMethod(IIntermediateClassType result, IIntermediateClassFieldMember charBufferSize, IIntermediateClassFieldMember charBuffer, IIntermediateCliManager identityManager)
        {
            /* *
             * Full Method:
             * if (this.buffer == null)
             * {
             *     this.buffer = new char[totalSize];
             *     return;
             * }
             * if (this.buffer.Length >= totalSize)
             *     return;
             * int pNew = this.buffer.Length * 2;
             * if (totalSize > pNew)
             *     pNew = totalSize;
             * char[] newBuffer = new char[pNew];
             * this.buffer.CopyTo(newBuffer, 0);
             * this.buffer = newBuffer;
             * */
            var growBufferMethod   = result.Methods.Add(new TypedName("GrowBuffer", identityManager.ObtainTypeReference(RuntimeCoreType.VoidType)));
            var totalSizeParameter = growBufferMethod.Parameters.Add(new TypedName("totalSize", identityManager.ObtainTypeReference(RuntimeCoreType.Int32)));
//          if (this.buffer == null)
//          {
            var nullCheck = growBufferMethod.If(charBuffer.GetReference().EqualTo(IntermediateGateway.NullValue));

//              this.buffer = new char[totalSize];
            nullCheck.Assign(charBuffer.GetReference(), new MalleableCreateArrayExpression(identityManager.ObtainTypeReference(RuntimeCoreType.Char), totalSizeParameter.GetReference()));
//              return;
//          }
            nullCheck.Return();
//          if (this.buffer.Length >= totalSize)
            var needCheck = growBufferMethod.If(charBuffer.GetReference().GetProperty("Length").GreaterThanOrEqualTo(totalSizeParameter));

//              return;
            needCheck.Return();

//          int pNew = this.actualSize * 2;
            var pNewVar = growBufferMethod.Locals.Add(new TypedName("pNew", identityManager.ObtainTypeReference(RuntimeCoreType.Int32)), charBufferSize.Multiply(2));

            //So it isn't declared automatically, thus causing a potential null reference exception.
            pNewVar.AutoDeclare = false;
            growBufferMethod.DefineLocal(pNewVar);
//          if (totalSize > pNew)
            var rangeCheck = growBufferMethod.If(totalSizeParameter.GreaterThan(pNewVar));

//              pNew = totalSize;
            rangeCheck.Assign(pNewVar.GetReference(), totalSizeParameter.GetReference());

//          char[] newBuffer = new char[pNew];
            var newBufferVar = growBufferMethod.Locals.Add(new TypedName("newBuffer", identityManager.ObtainTypeReference(RuntimeCoreType.Char).MakeArray()), new MalleableCreateArrayExpression(identityManager.ObtainTypeReference(RuntimeCoreType.Char), pNewVar.GetReference()));

            //So newBuffer doesn't refer to pNew before it is declared.
            newBufferVar.AutoDeclare = false;
            growBufferMethod.DefineLocal(newBufferVar);

//          this.buffer.CopyTo(newBuffer, 0);
            growBufferMethod.Call(charBuffer.GetReference().GetMethod("CopyTo").
                                  Invoke(newBufferVar.GetReference(), IntermediateGateway.NumberZero));

//          this.buffer = newBuffer;
            growBufferMethod.Assign(charBuffer.GetReference(), newBufferVar.GetReference());
            return(growBufferMethod);
        }
コード例 #20
0
        internal static IEnumerable <VisitorBuilder> GetVisitorContexts(IAssembly assembly, VisitorModelCommonTypeContext attributeContext, ICSharpAssembly resultAssembly, IIntermediateCliManager identityManager)
        {
            var visitorRelevantTypes = assembly.GetTypes().Where(t => t.Metadata.Contains(attributeContext.TargetAttribute)).ToArray();

            /* Using the metadata supplied on the relevant types, group them by their distinct visitor targets.
             * We'll use the distinct targets to generate concrete visitor interfaces.
             * The VisitorTargetAttribute allows multiple applications, so we may have multiple possible visitors for a single type. */
            var visitorContextualDetail = (from type in visitorRelevantTypes
                                           from metadatum in type.Metadata.Where(k => k.Type == attributeContext.TargetAttribute)
                                           let currentDetail = VisitorTargetDetail.DeriveFromMetadata(metadatum)
                                                               group type by currentDetail into distinctVisitorDetail
                                                               orderby distinctVisitorDetail.Key.TargetContext,
                                           string.IsNullOrEmpty(distinctVisitorDetail.Key.DerivedThroughInheriting)
                                                   ? string.Empty
                                                   : distinctVisitorDetail.Key.DerivedThroughInheriting,
                                           distinctVisitorDetail.Key.ContextualVisitor,
                                           distinctVisitorDetail.Key.YieldingVisitor
                                           select distinctVisitorDetail).ToDictionary(k => k.Key, v => new HashSet <IType>(v));

            /* Break the sets into two variations:
             * 1. Visitors which are derived from other visitors */
            var inheritanceBasedDetail =
                visitorContextualDetail.Keys.Where(k => !string.IsNullOrEmpty(k.DerivedThroughInheriting)).ToArray();
            /* 2. The concrete visitors which aren't representative of derivation.  There may be overlap. */
            var nonDerivedVisitors =
                visitorContextualDetail.Keys.Where(k => string.IsNullOrEmpty(k.DerivedThroughInheriting)).ToArray();

            var directVisitors = (from context in nonDerivedVisitors
                                  let builder = GetVisitorFrom(context, visitorContextualDetail[context], resultAssembly)
                                                select builder).ToDictionary(k => k.Detail, v => v);

            var inheritanceTree =
                (from detail in inheritanceBasedDetail
                 orderby detail.TargetContext, detail.DerivedThroughInheriting
                 /* We group by a *new* TargetVisitorDetail since we're not interested in the DerivedThroughInheriting, which would fragment the visitors. */
                 group detail.DerivedThroughInheriting by new VisitorTargetDetail {
                TargetContext = detail.TargetContext, ContextualVisitor = detail.ContextualVisitor, YieldingVisitor = detail.YieldingVisitor
            })
                .ToDictionary(k => k.Key, v => v.Distinct().ToArray());

            var inheritanceOnlyVisitors = new Dictionary <VisitorTargetDetail, VisitorBuilder>();

            foreach (var inheritanceKey in inheritanceTree.Keys)
            {
                var inheritedVisitorNames = inheritanceTree[inheritanceKey];
                var iovKey = new VisitorTargetDetail {
                    TargetContext = inheritanceKey.TargetContext, ContextualVisitor = inheritanceKey.ContextualVisitor, YieldingVisitor = inheritanceKey.YieldingVisitor
                };
                VisitorBuilder mainBuilder;
                if (!directVisitors.TryGetValue(inheritanceKey, out mainBuilder) && !inheritanceOnlyVisitors.TryGetValue(iovKey, out mainBuilder))
                {
                    inheritanceOnlyVisitors.Add(iovKey, mainBuilder = new VisitorBuilder(inheritanceKey));
                }

                var childBuilders =
                    (from childDetail in inheritedVisitorNames
                     .Select(k =>
                             GetRelevantDetail(nonDerivedVisitors, inheritanceKey, k))
                     select directVisitors.ContainsKey(childDetail)
                            ? directVisitors[childDetail]
                            : inheritanceOnlyVisitors.ContainsKey(childDetail)
                              ? inheritanceOnlyVisitors[childDetail]
                              : new VisitorBuilder(childDetail)).ToArray();
                foreach (var childBuilder in childBuilders.Where(childBuilder => childBuilder.VisitorInterface == null))
                {
                    inheritanceOnlyVisitors.Add(childBuilder.Detail, childBuilder);
                    childBuilder.ScaffoldInterface(resultAssembly);
                }
                if (mainBuilder.VisitorInterface == null)
                {
                    mainBuilder.SkippedTypes      =
                        mainBuilder.RelevantTypes =
                            childBuilders
                            .SelectMany(k => k.RelevantTypes)
                            .Distinct()
                            .ToList();
                    mainBuilder.ScaffoldInterface(resultAssembly);
                }
                mainBuilder.ChildBuilders = childBuilders;
                foreach (var childBuilder in childBuilders)
                {
                    mainBuilder.VisitorInterface.ImplementedInterfaces.Add(childBuilder.VisitorInterface);
                }
            }

            foreach (var builder in inheritanceOnlyVisitors.Values.Concat(directVisitors.Values))
            {
                builder.BuildVisitor();
            }

            return(inheritanceOnlyVisitors
                   .Values
                   .Concat(directVisitors.Values)
                   .OrderBy(k => k.Detail.TargetContext)
                   .ThenBy(k => k.Detail.ContextualVisitor)
                   .ThenBy(k => k.Detail.YieldingVisitor)
                   .ThenBy(k => string.IsNullOrEmpty(k.Detail.DerivedThroughInheriting) ? string.Empty : k.Detail.DerivedThroughInheriting)
                   .ToArray());
        }
コード例 #21
0
        private static IIntermediateClassMethodMember AddPushStringMethod(IIntermediateClassType result, IIntermediateClassFieldMember charBufferSize, IIntermediateClassFieldMember charBuffer, IIntermediateClassMethodMember growBufferMethod, IIntermediateCliManager identityManager)
        {
            /* *
             * Full Method:
             * if (buffer == null)
             *     GrowBuffer(s.Length);
             * else if (buffer.Length < actualSize + s.Length)
             *     GrowBuffer(actualSize + s.Length);
             * for (int i = 0; i < s.Length; i++)
             * {
             *     buffer[actualSize] = s[i];
             *     actualSize++;
             * }
             * */
            IIntermediateClassMethodMember pushStringMethod = result.Methods.Add(new TypedName("Push", identityManager.ObtainTypeReference(RuntimeCoreType.VoidType)));

            pushStringMethod.AccessLevel = AccessLevelModifiers.Public;
            var sParameter = pushStringMethod.Parameters.Add(new TypedName("s", identityManager.ObtainTypeReference(RuntimeCoreType.String)));
//          if (buffer == null)

            var nullCheck = pushStringMethod.If(charBuffer.GetReference().EqualTo(IntermediateGateway.NullValue));

//              GrowBuffer(s.Length);
            nullCheck.Call(growBufferMethod.GetReference().Invoke(sParameter.GetReference().GetProperty("Length")));
//          else if (buffer.Length < actualSize + s.Length)
            nullCheck.CreateNext(charBuffer.GetReference().GetProperty("Length").LessThan(charBufferSize.GetReference().Add(sParameter.GetReference().GetProperty("Length"))));
            var rangeCheck = (IConditionBlockStatement)nullCheck.Next;

//              GrowBuffer(actualSize + s.Length);
            rangeCheck.Call(growBufferMethod.GetReference().Invoke(charBufferSize.GetReference().Add(sParameter.GetReference().GetProperty("Length"))));

            //int i = 0;
            var iLocal = pushStringMethod.Locals.Add(new TypedName("i", identityManager.ObtainTypeReference(RuntimeCoreType.Int32)));

            //So it isn't declared in the main body.
            iLocal.InitializationExpression = IntermediateGateway.NumberZero;
            iLocal.AutoDeclare = false;
            //i++
//          for (int i = 0; i < s.Length; i++)
//          {
            var sToBufferIterate = pushStringMethod.Iterate(iLocal.GetDeclarationStatement(), iLocal.LessThan(sParameter.GetReference().GetProperty("Length")), new IStatementExpression[] { iLocal.Increment() });

            //var sToBufferIterate = pushStringMethod.Iterate(iLocal.GetDeclarationStatement(), IntermediateGateway.NumberZero, sParameter.GetReference().GetProperty("Length"));
//              buffer[actualSize++] = s[i];
            sToBufferIterate.Assign(charBuffer.GetReference().GetIndexer(charBufferSize.Increment()), sParameter.GetReference().GetIndexer(iLocal.GetReference()));
//          }
            return(pushStringMethod);
        }
コード例 #22
0
        private static void BuildVisitor(ParserCompiler compiler, IType returnType, IIntermediateInterfaceType visitorInterface, IIntermediateCliManager identityManager)
        {
            var    voidType = identityManager.ObtainTypeReference(RuntimeCoreType.VoidType);
            string rtType   = returnType.IsGenericTypeParameter ? "@t:" : "@s:";
            var    methods  = new Dictionary <IOilexerGrammarProductionRuleEntry, IIntermediateInterfaceMethodMember>();

            foreach (var rule in compiler.Source.GetRules() /*.Where(r => !r.IsRuleCollapsePoint)*/)
            {
                string ruleNameParameter = rule.Name.LowerFirstCharacter();
                var    targetInterface   = compiler.RuleDetail[rule].RelativeInterface;
                object target            = rule;
                if (rule.IsRuleCollapsePoint)
                {
                    continue;
                }
                AddVisitMethodToVisitor(returnType, visitorInterface, voidType, rtType, methods, ruleNameParameter, targetInterface, target);
            }

            var rootVisit = AddVisitMethodToClass(returnType, voidType, visitorInterface, compiler.RootRuleBuilder.LanguageRuleRoot, true, AddVisitMethodToInterface(returnType, visitorInterface, compiler.RootRuleBuilder.ILanguageRule));

            AddVisitMethodToInterface(returnType, visitorInterface, compiler.TokenSymbolBuilder.ILanguageToken);
            IIntermediateInterfaceMethodMember tokenSymbolVisitMethod;

            AddVisitMethodToClass(returnType, voidType, visitorInterface, compiler.VariableTokenBaseBuilder.LanguageVariableToken, false, AddVisitMethodToVisitor(returnType, visitorInterface, voidType, rtType, methods, "token", compiler.VariableTokenBaseBuilder.ILanguageVariableToken, null));
            AddVisitMethodToClass(returnType, voidType, visitorInterface, compiler.FixedTokenBaseBuilder.LanguageFixedToken, false, tokenSymbolVisitMethod = AddVisitMethodToVisitor(returnType, visitorInterface, voidType, rtType, methods, "token", compiler.TokenSymbolBuilder.ILanguageToken, null));

            foreach (var rule in compiler.Source.GetRules().Where(r => !r.IsRuleCollapsePoint))
            {
                BuildMethodOn(returnType, visitorInterface, voidType, methods[rule], compiler.RuleDetail[rule].Class);
            }

            visitorInterface.AccessLevel = AccessLevelModifiers.Public;
            var tokenDerived = compiler.TokenCastAsRule;

            if (tokenDerived != null)
            {
                var orm = compiler.RelationalModelMapping.ImplementationDetails[tokenDerived];
                var tokenDerivedVisit = BuildMethodOn(returnType, visitorInterface, voidType, null, orm.Value.Class, true);
                var call = rootVisit.GetReference(compiler.RootRuleBuilder.TokenDerived_Token.GetReference()).Invoke(tokenDerivedVisit.Parameters["visitor"].GetReference());
                if (voidType != returnType)
                {
                    tokenDerivedVisit.Return(call);
                }
                else
                {
                    tokenDerivedVisit.Call(call);
                }
            }
            //BuildMethodOn(returnType, visitorInterface, voidType, method, compiler.RelationalModelMapping[compiler.TokenCastAsRule].ImplementationDetails.Value.Class);
        }
コード例 #23
0
        private static IIntermediateClassMethodMember AddPushMethod(IIntermediateClassType result, IIntermediateClassFieldMember charBufferSize, IIntermediateClassFieldMember charBuffer, IIntermediateClassMethodMember growBufferMethod, IIntermediateCliManager identityManager)
        {
            /* *
             * Full Method:
             * if (buffer == null)
             *     GrowBuffer(2);
             * else if (buffer.Length < actualSize + 1)
             *     GrowBuffer(actualSize + 1);
             * buffer[actualSize] = c;
             * actualSize++;
             * */
            IIntermediateClassMethodMember pushMethod = result.Methods.Add(new TypedName("Push", identityManager.ObtainTypeReference(RuntimeCoreType.VoidType)));

            pushMethod.AccessLevel = AccessLevelModifiers.Public;
            var cParameter = pushMethod.Parameters.Add(new TypedName("c", identityManager.ObtainTypeReference(RuntimeCoreType.Char)));
//          if (buffer == null)
            var nullCheck = pushMethod.If(charBuffer.EqualTo(IntermediateGateway.NullValue));

//              GrowBuffer(2);
            nullCheck.Call(growBufferMethod.GetReference().Invoke(2.ToPrimitive()));
//          else if (buffer.Length < actualSize + 1)
            nullCheck.CreateNext(charBuffer.GetReference().GetProperty("Length").LessThan(charBufferSize.GetReference().Add(1.ToPrimitive())));
            var rangeCheck = (IConditionBlockStatement)nullCheck.Next;

//              GrowBuffer(actualSize + 1);
            rangeCheck.Call(growBufferMethod.GetReference().Invoke(charBufferSize.GetReference().Add(1.ToPrimitive())));
//          buffer[actualSize++] = c;
            pushMethod.Assign(charBuffer.GetReference().GetIndexer(charBufferSize.Increment()), cParameter.GetReference());
            return(pushMethod);
        }
コード例 #24
0
        private void BuildDebuggerDisplayForSymbols(ParserCompiler compiler, ParserBuilder parserBuilder, IIntermediateCliManager identityManager)
        {
            var extensionsClass = compiler.RuleSymbolBuilder.ILanguageRuleSymbol.Assembly.DefaultNamespace.Parts.Add().Classes.Add("{0}Extensions", compiler.Source.Options.AssemblyName);

            extensionsClass.AccessLevel     = AccessLevelModifiers.Internal;
            extensionsClass.SpecialModifier = SpecialClassModifier.Static;
            this.ExtensionsClass            = extensionsClass;
            var symbolDebuggerDisplay = extensionsClass.Methods.Add(
                new TypedName("SymbolDebuggerDisplay", RuntimeCoreType.String, identityManager),
                new TypedNameSeries(
                    new TypedName("symbol", compiler.SymbolStoreBuilder.Identities)));
            var symbol = symbolDebuggerDisplay.Parameters["symbol"];

            var constantEntries = (from s in compiler._GrammarSymbols.SymbolsOfType <IGrammarConstantEntrySymbol>()
                                   where !(s.Source is IOilexerGrammarTokenEofEntry)
                                   let literalItem = s.Source.Branches[0][0] as ILiteralTokenItem
                                                     where literalItem != null
                                                     orderby literalItem.Line, literalItem.Column, literalItem.Value.ToString()
                                   select new { LiteralItem = literalItem, Symbol = s }).ToArray();
            var constantItems =
                (from s in compiler._GrammarSymbols.SymbolsOfType <IGrammarConstantItemSymbol>()
                 let literalItem = s.SourceItem
                                   orderby literalItem.Line, literalItem.Column, literalItem.Value.ToString()
                 select new { LiteralItem = literalItem, Symbol = s }).ToArray();

            var ambiguousItems =
                (from s in compiler._GrammarSymbols.SymbolsOfType <IGrammarAmbiguousSymbol>()
                 let literalConstantEntry = (IGrammarConstantEntrySymbol)s.FirstOrDefault(aSym => aSym is IGrammarConstantEntrySymbol && constantEntries.Any(ce => ce.Symbol == aSym))
                                            let literalConstantItem = (IGrammarConstantItemSymbol)s.FirstOrDefault(aSym => aSym is IGrammarConstantItemSymbol && constantItems.Any(ci => ci.Symbol == aSym))
                                                                      where literalConstantEntry != null || literalConstantItem != null
                                                                      let literalItem = literalConstantEntry != null ? literalConstantEntry.Source.Branches[0][0] as ILiteralTokenItem : literalConstantItem.SourceItem
                                                                                        orderby literalItem.Line, literalItem.Column, literalItem.Value.ToString()
                 select new { LiteralItem = literalItem, Symbol = s }).ToArray();

            var mainSwitch = symbolDebuggerDisplay.Switch(symbol.GetReference());

            //compiler.TokenSymbolDetail
            foreach (var constantEntry in constantEntries)
            {
                var symbolDet   = compiler.TokenSymbolDetail[constantEntry.Symbol];
                var currentCase = mainSwitch.Case(symbolDet.Identity.GetReference());
                var fN          = symbolDet.Symbol.Source.FileName;
                if (fN.ToLower().StartsWith(compiler.Source.RelativeRoot))
                {
                    currentCase.Comment(string.Format("In .{0} on line {1}, column {2}", fN.Substring(compiler.Source.RelativeRoot.Length), constantEntry.LiteralItem.Line, constantEntry.LiteralItem.Column));
                }
                else
                {
                    currentCase.Comment(string.Format("In {0} on line {1}, column {2}", fN, constantEntry.LiteralItem.Line, constantEntry.LiteralItem.Column));
                }
                currentCase.Return(constantEntry.LiteralItem.Value.ToString().ToPrimitive());
            }
            foreach (var constantItem in constantItems)
            {
                var symbolDet   = compiler.TokenSymbolDetail[constantItem.Symbol];
                var currentCase = mainSwitch.Case(symbolDet.Identity.GetReference());
                var fN          = symbolDet.Symbol.Source.FileName;
                if (fN.ToLower().StartsWith(compiler.Source.RelativeRoot))
                {
                    currentCase.Comment(string.Format("In .{0} on line {1}, column {2}", fN.Substring(compiler.Source.RelativeRoot.Length), constantItem.LiteralItem.Line, constantItem.LiteralItem.Column));
                }
                else
                {
                    currentCase.Comment(string.Format("In {0} on line {1}, column {2}", fN, constantItem.LiteralItem.Line, constantItem.LiteralItem.Column));
                }
                currentCase.Return(constantItem.LiteralItem.Value.ToString().ToPrimitive());
            }

            foreach (var ambiguousItem in ambiguousItems)
            {
                var           identityField    = compiler.LexicalSymbolModel.GetIdentitySymbolField(ambiguousItem.Symbol);
                var           currentCase      = mainSwitch.Case(identityField.GetReference());
                StringBuilder ambiguityBuilder = new StringBuilder();
                ambiguityBuilder.Append("Ambiguity {");
                bool first = true;
                foreach (var ambigSymbol in ambiguousItem.Symbol)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        ambiguityBuilder.Append(", ");
                    }
                    ambiguityBuilder.Append(ambigSymbol.ElementName);
                }
                ambiguityBuilder.Append("} :");
                ambiguityBuilder.Append(ambiguousItem.LiteralItem.Value.ToString().ToPrimitive());
                currentCase.Return(ambiguityBuilder.ToString().ToPrimitive());
            }

            mainSwitch.Case(true).Return(symbol.GetReference().GetMethod("ToString").Invoke());

            this.SymbolDebuggerDisplay        = symbolDebuggerDisplay;
            symbolDebuggerDisplay.AccessLevel = AccessLevelModifiers.Public;
            compiler.SymbolStoreBuilder.Identities.Metadata.Add(new MetadatumDefinitionParameterValueCollection(identityManager.ObtainTypeReference(typeof(DebuggerDisplayAttribute)))
            {
                string.Format("{{{0}.{1}.{2}(this),nq}}", extensionsClass.NamespaceName, extensionsClass.Name, symbolDebuggerDisplay.Name)
            });
            compiler.FixedTokenBaseBuilder.LanguageFixedToken.Metadata.Add(new MetadatumDefinitionParameterValueCollection(identityManager.ObtainTypeReference(typeof(DebuggerDisplayAttribute)))
            {
                string.Format("{{{0}.{1}.{2}(Identity),nq}}", extensionsClass.NamespaceName, extensionsClass.Name, symbolDebuggerDisplay.Name)
            });
            compiler.VariableTokenBaseBuilder.LanguageVariableToken.Metadata.Add(new MetadatumDefinitionParameterValueCollection(identityManager.ObtainTypeReference(typeof(DebuggerDisplayAttribute)))
            {
                "{Value,nq}"
            });
            compiler.RootRuleBuilder.LanguageRuleRoot.Metadata.Add(new MetadatumDefinitionParameterValueCollection(identityManager.ObtainTypeReference(typeof(DebuggerDisplayAttribute)))
            {
                "{Context.Identity,nq}: {Context}"
            });
        }
コード例 #25
0
        private static IIntermediateClassMethodMember AddToStringMethod(IIntermediateClassType result, IIntermediateClassFieldMember charBufferSize, IIntermediateClassFieldMember charBuffer, IIntermediateCliManager identityManager)
        {
            /* *
             * Full method:
             * char[] result = new char[this.actualSize];
             * for (int i = 0; i < this.actualSize; i++)
             *     result[i] = buffer[i];
             * return new string(result);
             * */
            IIntermediateClassMethodMember toStringOverride = result.Methods.Add(new TypedName("ToString", identityManager.ObtainTypeReference(RuntimeCoreType.String)));

            toStringOverride.AccessLevel = AccessLevelModifiers.Public;
            toStringOverride.IsOverride  = true;
            //char[] result = new char[this.actualSize];
            var resultCharsInitExp = new MalleableCreateArrayDetailExpression(identityManager.ObtainTypeReference(RuntimeCoreType.Char));

            resultCharsInitExp.Sizes.Add(charBufferSize.GetReference());
            var resultChars = toStringOverride.Locals.Add(new TypedName("result", identityManager.ObtainTypeReference(RuntimeCoreType.Char).MakeArray()), resultCharsInitExp);

            var iLocal = toStringOverride.Locals.Add(new TypedName("i", identityManager.ObtainTypeReference(RuntimeCoreType.Int32)));

            //int i = 0;
            iLocal.InitializationExpression = IntermediateGateway.NumberZero;
            //So it isn't declared in the main body.
            iLocal.AutoDeclare = false;
            //i++

            var increment = iLocal.Increment();
            //for (int i = 0; i < this.actualSize; i++)

            var loop = toStringOverride.Iterate(iLocal.GetDeclarationStatement(), iLocal.LessThan(charBufferSize), new IStatementExpression[] { increment });

            //    result[i] = this.buffer[i];
            loop.Assign(resultChars.GetReference().GetIndexer(iLocal.GetReference()), charBuffer.GetReference().GetIndexer(iLocal.GetReference()));
            //return new string(result);
            toStringOverride.Return(identityManager.ObtainTypeReference(RuntimeCoreType.String).GetNewExpression(resultChars.GetReference()));
            return(toStringOverride);
        }
コード例 #26
0
 public ICSharpProvider GetProvider(CSharpLanguageVersion version, IIntermediateCliManager identityManager)
 {
     return(new CSharpProvider(version, identityManager));
 }
コード例 #27
0
 public ICoreVisualBasicProvider GetProvider(IIntermediateCliManager identityManager)
 {
     return(this.GetProvider(VisualBasicVersion.CurrentVersion, identityManager));
 }
コード例 #28
0
 public ICoreVisualBasicProvider GetProvider(VisualBasicVersion version, IIntermediateCliManager identityManager)
 {
     return(new CoreVisualBasicProvider(version, identityManager));
 }
コード例 #29
0
 public ICSharpProvider GetProvider(IIntermediateCliManager identityManager)
 {
     return(GetProvider(CSharpLanguageVersion.CurrentVersion, identityManager));
 }
コード例 #30
0
        private void BuildGetValidSyntaxCore(ParserCompiler compiler, ParserBuilder parserBuilder, IIntermediateCliManager identityManager)
        {
            var targetClassPartial = parserBuilder.ParserClass.Parts.Add();

            this._getValidSyntaxMethodImpl         = targetClassPartial.Methods.Add(new TypedName("GetValidSyntax", compiler.LexicalSymbolModel.ValidSymbols));
            this._getValidSyntaxMethod             = parserBuilder.ParserInterface.Methods.Add(new TypedName("GetValidSyntax", compiler.LexicalSymbolModel.ValidSymbols));
            this._getValidSyntaxMethodInternalImpl =
                targetClassPartial.Methods.Add(
                    new TypedName("GetValidSyntaxInternal", compiler.LexicalSymbolModel.ValidSymbols),
                    new TypedNameSeries(
                        new TypedName("state", RuntimeCoreType.Int32, identityManager),
                        new TypedName("ruleContext", compiler.RuleSymbolBuilder.ILanguageRuleSymbol),
                        new TypedName("initialPass", RuntimeCoreType.Boolean, identityManager)));
        }