/// <summary>
        /// This method is called to create a C# Symbol as a token
        /// </summary>
        /// <param name="start">Start position in the source document of the Token</param>
        /// <param name="content">the lexeme of the token</param>
        /// <param name="type">The Token's type</param>
        /// <param name="errors">Any encountered error</param>
        /// <returns>The Token's symbol</returns>
        protected override CSharpSymbol CreateSymbol(SourceLocation start, string content, CSharpSymbolType type,
                                                     IEnumerable <RazorError> errors)
        {
            CSharpSymbol symbol = base.CreateSymbol(start, content, type, errors);

            return(symbol);
        }
Esempio n. 2
0
 private static string GetName(CSharpSymbol sym)
 {
     if (sym.Type == CSharpSymbolType.Keyword)
     {
         return(CSharpLanguageCharacteristics.GetKeyword(sym.Keyword.Value));
     }
     return(sym.Content);
 }
Esempio n. 3
0
        private bool IsAcceptableIdentifierReplacement(Span target, TextChange change)
        {
            if (!change.IsReplace)
            {
                return(false);
            }

            foreach (ISymbol isymbol in target.Symbols)
            {
                CSharpSymbol symbol = isymbol as CSharpSymbol;

                if (symbol == null)
                {
                    break;
                }

                int symbolStartIndex = target.Start.AbsoluteIndex + symbol.Start.AbsoluteIndex;
                int symbolEndIndex   = symbolStartIndex + symbol.Content.Length;

                // We're looking for the first symbol that contains the TextChange.
                if (symbolEndIndex > change.OldPosition)
                {
                    if (
                        symbolEndIndex >= change.OldPosition + change.OldLength &&
                        symbol.Type == CSharpSymbolType.Identifier
                        )
                    {
                        // The symbol we're changing happens to be an identifier. Need to check if its transformed state is also one.
                        // We do this transformation logic to capture the case that the new text change happens to not be an identifier;
                        // i.e. "5". Alone, it's numeric, within an identifier it's classified as identifier.
                        string transformedContent = change.ApplyChange(
                            symbol.Content,
                            symbolStartIndex
                            );
                        IEnumerable <ISymbol> newSymbols = Tokenizer(transformedContent);

                        if (newSymbols.Count() != 1)
                        {
                            // The transformed content resulted in more than one symbol; we can only replace a single identifier with
                            // another single identifier.
                            break;
                        }

                        CSharpSymbol newSymbol = (CSharpSymbol)newSymbols.First();
                        if (newSymbol.Type == CSharpSymbolType.Identifier)
                        {
                            return(true);
                        }
                    }
                    // Change is touching a non-identifier symbol or spans multiple symbols.

                    break;
                }
            }

            return(false);
        }
Esempio n. 4
0
        /// <summary>
        /// Static method for dumping the tokenization of a string content.
        /// </summary>
        /// <param name="content">The string content to dump the tokenization</param>
        public static void DumpTokens(string content)
        {
            SeekableTextReader   reader    = new SeekableTextReader(new StringReader(content));
            CSharpRazorTokenizer tokenizer = new CSharpRazorTokenizer(reader);
            CSharpSymbol         csSym     = null;

            while ((csSym = tokenizer.NextSymbol()) != null)
            {
                System.Diagnostics.Debug.Write(csSym.Content);
            }
        }
Esempio n. 5
0
        string GetStyleForChunk(CSharpSymbol symbol, CSharpSymbol prevSymbol, int off)
        {
            if (prevSymbol != null)
            {
                // Razor directives, statements and expressions
                if (prevSymbol.Type == CSharpSymbolType.Transition)
                {
                    return(GetStyleForRazorFragment(symbol));
                }
                // End of Razor comments
                if (prevSymbol.Type == CSharpSymbolType.Star && symbol.Type == CSharpSymbolType.Transition)
                {
                    chunks.Last().Style = "Xml Comment";
                    return("Xml Comment");
                }
                // Email addresses
                if (symbol.Type == CSharpSymbolType.Transition && Char.IsLetterOrDigit(prevSymbol.Content.Last()))
                {
                    return("Plain Text");
                }
                // Html tags
                char c = symbol.Content.First();
                if ((!symbol.Keyword.HasValue && prevSymbol.Type == CSharpSymbolType.LessThan && (Char.IsLetterOrDigit(c) || c == '/')) ||
                    (prevSymbol.Type == CSharpSymbolType.Slash && currentState == State.InTag))
                {
                    currentState = State.InTag;
                    chunks.Last().Style = "Xml Name";
                    return("Xml Name");
                }
                if (symbol.Type == CSharpSymbolType.GreaterThan && currentState == State.InTag)
                {
                    currentState = State.None;
                    if (prevSymbol.Type == CSharpSymbolType.Slash)
                    {
                        chunks.Last().Style = "Xml Name";
                    }
                    return("Xml Name");
                }
            }
            if (symbol.Type == CSharpSymbolType.RightBrace || symbol.Type == CSharpSymbolType.RightParenthesis)
            {
                return(GetStyleForEndBracket(symbol, off));
            }
            // Text in html tags
            if ((symbol.Keyword.HasValue || symbol.Type == CSharpSymbolType.IntegerLiteral || symbol.Type == CSharpSymbolType.RealLiteral) &&
                IsInHtmlContext(symbol, off))
            {
                return("Plain Text");
            }

            return(GetStyleForCSharpSymbol(symbol));
        }
Esempio n. 6
0
        string GetStyleForEndBracket(CSharpSymbol symbol, int off)
        {
            int matchingOff = doc.GetMatchingBracketOffset(off);

            if (matchingOff == -1 || doc.GetCharAt(matchingOff - 1) != '@')
            {
                return("Plain Text");
            }
            else
            {
                return("Html Server-Side Script");
            }
        }
Esempio n. 7
0
 string GetStyleForRazorFragment(CSharpSymbol symbol)
 {
     if (symbol.Type == CSharpSymbolType.LeftParenthesis || symbol.Type == CSharpSymbolType.LeftBrace ||
         RazorSymbols.IsDirective(symbol.Content))
     {
         return("Html Server-Side Script");
     }
     if (symbol.Type == CSharpSymbolType.Star)
     {
         return("Xml Comment");
     }
     return(GetStyleForCSharpSymbol(symbol));
 }
Esempio n. 8
0
 string GetStyleForRazorFragment(CSharpSymbol symbol)
 {
     if (symbol.Type == CSharpSymbolType.LeftParenthesis || symbol.Type == CSharpSymbolType.LeftBrace ||
         RazorSymbols.IsDirective(symbol.Content))
     {
         return("template.tag");
     }
     if (symbol.Type == CSharpSymbolType.Star)
     {
         return("comment");
     }
     return(GetStyleForCSharpSymbol(symbol));
 }
Esempio n. 9
0
        string GetStyleForEndBracket(CSharpSymbol symbol, int off)
        {
            int matchingOff = doc.GetMatchingBracketOffset(off);

            if (matchingOff == -1 || doc.GetCharAt(matchingOff - 1) != '@')
            {
                return("text");
            }
            else
            {
                return("template.tag");
            }
        }
Esempio n. 10
0
        private void EmbeddedExpression()
        {
            // First, verify the type of the block
            Assert(CSharpSymbolType.Transition);
            CSharpSymbol transition = CurrentSymbol;

            NextToken();

            if (At(CSharpSymbolType.Transition))
            {
                // Escaped "@"
                Output(SpanKind.Code);

                // Output "@" as hidden span
                Accept(transition);
                Span.CodeGenerator = SpanCodeGenerator.Null;
                Output(SpanKind.Code);

                Assert(CSharpSymbolType.Transition);
                AcceptAndMoveNext();
                StandardStatement();
            }
            else
            {
                // Throw errors as necessary, but continue parsing
                if (At(CSharpSymbolType.Keyword))
                {
                    Context.OnError(
                        CurrentLocation,
                        RazorResources.ParseError_Unexpected_Keyword_After_At,
                        CSharpLanguageCharacteristics.GetKeyword(CurrentSymbol.Keyword.Value)
                        );
                }
                else if (At(CSharpSymbolType.LeftBrace))
                {
                    Context.OnError(
                        CurrentLocation,
                        RazorResources.ParseError_Unexpected_Nested_CodeBlock
                        );
                }

                // @( or @foo - Nested expression, parse a child block
                PutCurrentBack();
                PutBack(transition);

                // Before exiting, add a marker span if necessary
                AddMarkerSymbolIfNecessary();

                NestedBlock();
            }
        }
Esempio n. 11
0
        bool IsInHtmlContext(CSharpSymbol symbol, int off)
        {
            if (currentSpans == null)
            {
                CreateSpans();
            }
            var owner = currentSpans.LastOrDefault(s => s.Start.AbsoluteIndex <= off);

            if (owner != null && owner.Kind == System.Web.Razor.Parser.SyntaxTree.SpanKind.Markup)
            {
                return(true);
            }
            return(false);
        }
        protected void BaseTypeDirective(
            string noTypeNameError,
            Func <string, SpanCodeGenerator> createCodeGenerator
            )
        {
            // Set the block type
            Context.CurrentBlock.Type = BlockType.Directive;

            // Accept whitespace
            CSharpSymbol remainingWs = AcceptSingleWhiteSpaceCharacter();

            if (Span.Symbols.Count > 1)
            {
                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;
            }

            Output(SpanKind.MetaCode);

            if (remainingWs != null)
            {
                Accept(remainingWs);
            }
            AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true));

            if (EndOfFile || At(CSharpSymbolType.WhiteSpace) || At(CSharpSymbolType.NewLine))
            {
                Context.OnError(CurrentLocation, noTypeNameError);
            }

            // Parse to the end of the line
            AcceptUntil(CSharpSymbolType.NewLine);
            if (!Context.DesignTimeMode)
            {
                // We want the newline to be treated as code, but it causes issues at design-time.
                Optional(CSharpSymbolType.NewLine);
            }

            // Pull out the type name
            string baseType = Span.GetContent();

            // Set up code generation
            Span.CodeGenerator = createCodeGenerator(baseType.Trim());

            // Output the span and finish the block
            CompleteBlock();
            Output(SpanKind.Code);
        }
Esempio n. 13
0
        string GetStyleForCSharpSymbol(CSharpSymbol symbol)
        {
            if (symbol.Content == "var" || symbol.Content == "dynamic")
            {
                return("keyword.type");
            }

            string style = "text";

            switch (symbol.Type)
            {
            case CSharpSymbolType.CharacterLiteral:
            case CSharpSymbolType.StringLiteral:
                style = "string";
                break;

            case CSharpSymbolType.Comment:
                style = "comment";
                break;

            case CSharpSymbolType.IntegerLiteral:
            case CSharpSymbolType.RealLiteral:
                style = "constant.digit";
                break;

            case CSharpSymbolType.Keyword:
                style = GetStyleForKeyword(symbol.Keyword);
                break;

            case CSharpSymbolType.RazorComment:
            case CSharpSymbolType.RazorCommentStar:
            case CSharpSymbolType.RazorCommentTransition:
                style = "comment";
                break;

            case CSharpSymbolType.Transition:
                style = "template.tag";
                break;

            default:
                style = "text";
                break;
            }

            return(style);
        }
Esempio n. 14
0
        string GetStyleForCSharpSymbol(CSharpSymbol symbol)
        {
            if (symbol.Content == "var" || symbol.Content == "dynamic")
            {
                return("Keyword(Type)");
            }

            string style = "Plain Text";

            switch (symbol.Type)
            {
            case CSharpSymbolType.CharacterLiteral:
            case CSharpSymbolType.StringLiteral:
                style = "String";
                break;

            case CSharpSymbolType.Comment:
                style = "Xml Comment";
                break;

            case CSharpSymbolType.IntegerLiteral:
            case CSharpSymbolType.RealLiteral:
                style = "Number";
                break;

            case CSharpSymbolType.Keyword:
                style = GetStyleForKeyword(symbol.Keyword);
                break;

            case CSharpSymbolType.RazorComment:
            case CSharpSymbolType.RazorCommentStar:
            case CSharpSymbolType.RazorCommentTransition:
                style = "Xml Comment";
                break;

            case CSharpSymbolType.Transition:
                style = "Html Server-Side Script";
                break;

            default:
                style = "Plain Text";
                break;
            }

            return(style);
        }
        protected void SessionStateTypeDirective(
            string noValueError,
            Func <string, string, SpanCodeGenerator> createCodeGenerator
            )
        {
            // Set the block type
            Context.CurrentBlock.Type = BlockType.Directive;

            // Accept whitespace
            CSharpSymbol remainingWs = AcceptSingleWhiteSpaceCharacter();

            if (Span.Symbols.Count > 1)
            {
                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;
            }

            Output(SpanKind.MetaCode);

            if (remainingWs != null)
            {
                Accept(remainingWs);
            }
            AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true));

            // Parse a Type Name
            if (!ValidSessionStateValue())
            {
                Context.OnError(CurrentLocation, noValueError);
            }

            // Pull out the type name
            string sessionStateValue = String
                                       .Concat(Span.Symbols.Cast <CSharpSymbol>().Select(sym => sym.Content))
                                       .Trim();

            // Set up code generation
            Span.CodeGenerator = createCodeGenerator(
                SyntaxConstants.CSharp.SessionStateKeyword,
                sessionStateValue
                );

            // Output the span and finish the block
            CompleteBlock();
            Output(SpanKind.Code);
        }
Esempio n. 16
0
        public override IEnumerable <Chunk> GetChunks(ColorScheme style, DocumentLine line, int offset, int length)
        {
            // Multiline comment
            if (line.StartSpan.Count != 0 && line.StartSpan.Peek().Begin.Pattern == "@*")
            {
                return(base.GetChunks(style, line, offset, length));
            }

            var tokenizer = new CSharpTokenizer(new SeekableTextReader(doc.GetTextAt(offset, length)));

            chunks = new List <Chunk> ();
            CSharpSymbol symbol;
            CSharpSymbol prevSymbol = null;
            int          off        = offset;

            currentState = State.None;

            while ((symbol = tokenizer.NextSymbol()) != null)
            {
                // Apostrophes in text
                bool inApostrophes = false;
                if (symbol.Type == CSharpSymbolType.CharacterLiteral && prevSymbol != null && Char.IsLetterOrDigit(prevSymbol.Content.Last()))
                {
                    if (symbol.Content.Last() == '\'')
                    {
                        inApostrophes = true;
                    }
                    else
                    {
                        chunks.Add(new Chunk(off, 1, "Plain Text"));
                        off++;
                        tokenizer  = new CSharpTokenizer(new SeekableTextReader(symbol.Content.Substring(1)));
                        symbol     = tokenizer.NextSymbol();
                        prevSymbol = null;
                    }
                }

                string chunkStyle = inApostrophes ? "Plain Text" : GetStyleForChunk(symbol, prevSymbol, off);
                chunks.Add(new Chunk(off, symbol.Content.Length, chunkStyle));
                prevSymbol = symbol;
                off       += symbol.Content.Length;
            }

            return(chunks);
        }
Esempio n. 17
0
 public Symbol GetSymbol(CSharpSymbol csharpSymbol)
 {
     if (csharpSymbol is CSharpSymbols.AssemblySymbol assembly)
     {
         return(GetAssemblySymbol(assembly));
     }
     if (csharpSymbol is CSharpSymbols.ModuleSymbol module)
     {
         return(GetModuleSymbol(module));
     }
     if (csharpSymbol is CSharpSymbols.NamespaceSymbol ns)
     {
         return(GetNamespaceSymbol(ns));
     }
     if (csharpSymbol is CSharpSymbols.NamedTypeSymbol namedType)
     {
         return(GetNamedTypeSymbol(namedType));
     }
     return(new UnsupportedSymbol(csharpSymbol, GetSymbol(csharpSymbol.ContainingSymbol)));
 }
Esempio n. 18
0
        public void IsCSharpSymbolTest()
        {
            //
            // Using reflection, verify that all symbol constants are determined
            // to be symbols.
            //
            FieldInfo[] symbolFields = typeof(CSharpSymbol).GetFields(
                BindingFlags.Static | BindingFlags.Public);
            foreach (FieldInfo symbolField in symbolFields)
            {
                if (symbolField.FieldType == typeof(char))
                {
                    char fieldValue = (char)symbolField.GetValue(null);
                    Assert.IsTrue(CSharpSymbol.IsCSharpSymbol(fieldValue), "Field value should be considered a C# symbol.");
                }
            }

            Assert.IsFalse(CSharpSymbol.IsCSharpSymbol('1'));
            Assert.IsFalse(CSharpSymbol.IsCSharpSymbol('A'));
            Assert.IsFalse(CSharpSymbol.IsCSharpSymbol('$'));
            Assert.IsFalse(CSharpSymbol.IsCSharpSymbol('_'));
        }
 private static string GetName(CSharpSymbol sym)
 {
     if (sym.Type == CSharpSymbolType.Keyword)
     {
         return CSharpLanguageCharacteristics.GetKeyword(sym.Keyword.Value);
     }
     return sym.Content;
 }
 public Block(CSharpSymbol symbol)
     : this(GetName(symbol), symbol.Start)
 {
 }
Esempio n. 21
0
 public static UnclassifiedCodeSpanConstructor EmptyCSharp(this SpanFactory self)
 {
     var symbol = new CSharpSymbol(self.LocationTracker.CurrentLocation, string.Empty, CSharpSymbolType.Unknown);
     return new UnclassifiedCodeSpanConstructor(self.Span(SpanKind.Code, symbol));
 }
		string GetStyleForEndBracket (CSharpSymbol symbol, int off)
		{
			int matchingOff = doc.GetMatchingBracketOffset (off);
			if (matchingOff == -1 || doc.GetCharAt (matchingOff - 1) != '@')
				return "Plain Text";
			else
				return "Html Server-Side Script";
		}
		string GetStyleForChunk (CSharpSymbol symbol, CSharpSymbol prevSymbol, int off)
		{
			if (prevSymbol != null) {
				// Razor directives, statements and expressions
				if (prevSymbol.Type == CSharpSymbolType.Transition)
					return GetStyleForRazorFragment (symbol);
				// End of Razor comments
				if (prevSymbol.Type == CSharpSymbolType.Star && symbol.Type == CSharpSymbolType.Transition) {
					chunks.Last ().Style = "Xml Comment";
					return "Xml Comment";
				}
				// Email addresses
				if (symbol.Type == CSharpSymbolType.Transition && Char.IsLetterOrDigit (prevSymbol.Content.Last ()))
					return "Plain Text";
				// Html tags
				char c = symbol.Content.First ();
				if ((!symbol.Keyword.HasValue && prevSymbol.Type == CSharpSymbolType.LessThan && (Char.IsLetterOrDigit (c) || c == '/'))
					|| (prevSymbol.Type == CSharpSymbolType.Slash && currentState == State.InTag)) {
					currentState = State.InTag;
					chunks.Last ().Style = "Xml Name";
					return "Xml Name";
				}
				if (symbol.Type == CSharpSymbolType.GreaterThan && currentState == State.InTag) {
					currentState = State.None;
					if (prevSymbol.Type == CSharpSymbolType.Slash)
						chunks.Last ().Style = "Xml Name";
					return "Xml Name";
				}
			}
			if (symbol.Type == CSharpSymbolType.RightBrace || symbol.Type == CSharpSymbolType.RightParenthesis)
				return GetStyleForEndBracket (symbol, off);
			// Text in html tags
			if ((symbol.Keyword.HasValue || symbol.Type == CSharpSymbolType.IntegerLiteral || symbol.Type == CSharpSymbolType.RealLiteral)
				&& IsInHtmlContext (symbol, off))
				return "Plain Text";

			return GetStyleForCSharpSymbol (symbol);
		}
        public static UnclassifiedCodeSpanConstructor EmptyCSharp(this SpanFactory self)
        {
            var symbol = new CSharpSymbol(self.LocationTracker.CurrentLocation, string.Empty, CSharpSymbolType.Unknown);

            return(new UnclassifiedCodeSpanConstructor(self.Span(SpanKind.Code, symbol)));
        }
Esempio n. 25
0
        protected virtual void HelperDirective()
        {
            bool nested = Context.IsWithin(BlockType.Helper);

            // Set the block and span type
            Context.CurrentBlock.Type = BlockType.Helper;

            // Verify we're on "helper" and accept
            AssertDirective(SyntaxConstants.CSharp.HelperKeyword);
            Block block = new Block(CurrentSymbol.Content.ToString().ToLowerInvariant(), CurrentLocation);

            AcceptAndMoveNext();

            if (nested)
            {
                Context.OnError(CurrentLocation, RazorResources.ParseError_Helpers_Cannot_Be_Nested);
            }

            // Accept a single whitespace character if present, if not, we should stop now
            if (!At(CSharpSymbolType.WhiteSpace))
            {
                string error;
                if (At(CSharpSymbolType.NewLine))
                {
                    error = RazorResources.ErrorComponent_Newline;
                }
                else if (EndOfFile)
                {
                    error = RazorResources.ErrorComponent_EndOfFile;
                }
                else
                {
                    error = String.Format(CultureInfo.CurrentCulture, RazorResources.ErrorComponent_Character, CurrentSymbol.Content);
                }

                Context.OnError(
                    CurrentLocation,
                    RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,
                    error);
                PutCurrentBack();
                Output(SpanKind.MetaCode);
                return;
            }

            CSharpSymbol remainingWs = AcceptSingleWhiteSpaceCharacter();

            // Output metacode and continue
            Output(SpanKind.MetaCode);
            if (remainingWs != null)
            {
                Accept(remainingWs);
            }
            AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true)); // Don't accept newlines.

            // Expecting an identifier (helper name)
            bool errorReported = !Required(CSharpSymbolType.Identifier, errorIfNotFound: true, errorBase: RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start);

            if (!errorReported)
            {
                Assert(CSharpSymbolType.Identifier);
                AcceptAndMoveNext();
            }

            AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true));

            // Expecting parameter list start: "("
            SourceLocation bracketErrorPos = CurrentLocation;

            if (!Optional(CSharpSymbolType.LeftParenthesis))
            {
                if (!errorReported)
                {
                    errorReported = true;
                    Context.OnError(
                        CurrentLocation,
                        RazorResources.ParseError_MissingCharAfterHelperName,
                        "(");
                }
            }
            else
            {
                SourceLocation bracketStart = CurrentLocation;
                if (!Balance(BalancingModes.NoErrorOnFailure,
                             CSharpSymbolType.LeftParenthesis,
                             CSharpSymbolType.RightParenthesis,
                             bracketStart))
                {
                    errorReported = true;
                    Context.OnError(
                        bracketErrorPos,
                        RazorResources.ParseError_UnterminatedHelperParameterList);
                }
                Optional(CSharpSymbolType.RightParenthesis);
            }

            int bookmark = CurrentLocation.AbsoluteIndex;
            IEnumerable <CSharpSymbol> ws = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: true));

            // Expecting a "{"
            SourceLocation errorLocation  = CurrentLocation;
            bool           headerComplete = At(CSharpSymbolType.LeftBrace);

            if (headerComplete)
            {
                Accept(ws);
                AcceptAndMoveNext();
            }
            else
            {
                Context.Source.Position = bookmark;
                NextToken();
                AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true));
                if (!errorReported)
                {
                    Context.OnError(
                        errorLocation,
                        RazorResources.ParseError_MissingCharAfterHelperParameters,
                        Language.GetSample(CSharpSymbolType.LeftBrace));
                }
            }

            // Grab the signature and build the code generator
            AddMarkerSymbolIfNecessary();
            LocationTagged <string> signature = Span.GetContent();
            HelperCodeGenerator     blockGen  = new HelperCodeGenerator(signature, headerComplete);

            Context.CurrentBlock.CodeGenerator = blockGen;

            // The block will generate appropriate code,
            Span.CodeGenerator = SpanCodeGenerator.Null;

            if (!headerComplete)
            {
                CompleteBlock();
                Output(SpanKind.Code);
                return;
            }
            else
            {
                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;
                Output(SpanKind.Code);
            }

            // We're valid, so parse the nested block
            AutoCompleteEditHandler bodyEditHandler = new AutoCompleteEditHandler(Language.TokenizeString);

            using (PushSpanConfig(DefaultSpanConfig))
            {
                using (Context.StartBlock(BlockType.Statement))
                {
                    Span.EditHandler = bodyEditHandler;
                    CodeBlock(false, block);
                    CompleteBlock(insertMarkerIfNecessary: true);
                    Output(SpanKind.Code);
                }
            }
            Initialize(Span);

            EnsureCurrent();

            Span.CodeGenerator = SpanCodeGenerator.Null; // The block will generate the footer code.
            if (!Optional(CSharpSymbolType.RightBrace))
            {
                // The } is missing, so set the initial signature span to use it as an autocomplete string
                bodyEditHandler.AutoCompleteString = "}";

                // Need to be able to accept anything to properly handle the autocomplete
                bodyEditHandler.AcceptedCharacters = AcceptedCharacters.Any;
            }
            else
            {
                blockGen.Footer = Span.GetContent();
                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;
            }
            CompleteBlock();
            Output(SpanKind.Code);
        }
		string GetStyleForRazorFragment (CSharpSymbol symbol)
		{
			if (symbol.Type == CSharpSymbolType.LeftParenthesis || symbol.Type == CSharpSymbolType.LeftBrace
				|| RazorSymbols.IsDirective (symbol.Content))
				return "Html Server-Side Script";
			if (symbol.Type == CSharpSymbolType.Star)
				return "Xml Comment";
			return GetStyleForCSharpSymbol (symbol);
		}
Esempio n. 27
0
 public Block(CSharpSymbol symbol) : this(GetName(symbol), symbol.Start)
 {
 }
		bool IsInHtmlContext (CSharpSymbol symbol, int off)
		{
			if (currentSpans == null)
				CreateSpans ();
			var owner = currentSpans.LastOrDefault (s => s.Start.AbsoluteIndex <= off);
			if (owner != null && owner.Kind == System.Web.Razor.Parser.SyntaxTree.SpanKind.Markup)
				return true;
			return false;
		}
Esempio n. 29
0
        private void Statement(Block block)
        {
            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any;

            // Accept whitespace but always keep the last whitespace node so we can put it back if necessary
            CSharpSymbol lastWs = AcceptWhiteSpaceInLines();

            Debug.Assert(
                lastWs == null ||
                (
                    lastWs.Start.AbsoluteIndex + lastWs.Content.Length
                    == CurrentLocation.AbsoluteIndex
                )
                );

            if (EndOfFile)
            {
                if (lastWs != null)
                {
                    Accept(lastWs);
                }
                return;
            }

            CSharpSymbolType type = CurrentSymbol.Type;
            SourceLocation   loc  = CurrentLocation;

            bool isSingleLineMarkup =
                type == CSharpSymbolType.Transition && NextIs(CSharpSymbolType.Colon);
            bool isMarkup =
                isSingleLineMarkup ||
                type == CSharpSymbolType.LessThan ||
                (type == CSharpSymbolType.Transition && NextIs(CSharpSymbolType.LessThan));

            if (Context.DesignTimeMode || !isMarkup)
            {
                // CODE owns whitespace, MARKUP owns it ONLY in DesignTimeMode.
                if (lastWs != null)
                {
                    Accept(lastWs);
                }
            }
            else
            {
                // MARKUP owns whitespace EXCEPT in DesignTimeMode.
                PutCurrentBack();
                PutBack(lastWs);
            }

            if (isMarkup)
            {
                if (type == CSharpSymbolType.Transition && !isSingleLineMarkup)
                {
                    Context.OnError(
                        loc,
                        RazorResources.ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start
                        );
                }

                // Markup block
                Output(SpanKind.Code);
                if (
                    Context.DesignTimeMode &&
                    CurrentSymbol != null &&
                    (
                        CurrentSymbol.Type == CSharpSymbolType.LessThan ||
                        CurrentSymbol.Type == CSharpSymbolType.Transition
                    )
                    )
                {
                    PutCurrentBack();
                }
                OtherParserBlock();
            }
            else
            {
                // What kind of statement is this?
                HandleStatement(block, type);
            }
        }
		string GetStyleForCSharpSymbol (CSharpSymbol symbol)
		{
			if (symbol.Content == "var" || symbol.Content == "dynamic")
				return "Keyword(Type)";

			string style = "Plain Text";
			switch (symbol.Type) {
				case CSharpSymbolType.CharacterLiteral:
				case CSharpSymbolType.StringLiteral:
					style = "String";
					break;
				case CSharpSymbolType.Comment:
					style = "Xml Comment";
					break;
				case CSharpSymbolType.IntegerLiteral:
				case CSharpSymbolType.RealLiteral:
					style = "Number";
					break;
				case CSharpSymbolType.Keyword:
					style = GetStyleForKeyword (symbol.Keyword);
					break;
				case CSharpSymbolType.RazorComment:
				case CSharpSymbolType.RazorCommentStar:
				case CSharpSymbolType.RazorCommentTransition:
					style = "Xml Comment";
					break;
				case CSharpSymbolType.Transition:
					style = "Html Server-Side Script";
					break;
				default:
					style = "Plain Text";
					break;
			}

			return style;
		}