Beispiel #1
0
 public string Generate(LiteralExpressionSyntax literal, SemanticModel semanticModel)
 {
     if (literal.IsKind(SyntaxKind.NullLiteralExpression))
     {
         return("null");
     }
     if (literal.IsKind(SyntaxKind.TrueLiteralExpression))
     {
         return("true");
     }
     if (literal.IsKind(SyntaxKind.FalseLiteralExpression))
     {
         return("false");
     }
     if (literal.IsKind(SyntaxKind.NumericLiteralExpression))
     {
         return(literal.ToString());
     }
     if (literal.IsKind(SyntaxKind.StringLiteralExpression))
     {
         return(literal.ToString());
     }
     if (literal.IsKind(SyntaxKind.CharacterLiteralExpression))
     {
         return(literal.ToString());
     }
     throw new NotImplementedException();
 }
Beispiel #2
0
 /// <summary>
 /// リテラル式構文のTypeScript変換
 /// </summary>
 /// <param name="condition">ExpressionSyntaxインスタンス</param>
 /// <param name="localDeclarationStatements">ローカル変数リスト</param>
 /// <returns>TypeScriptに変換した文字列</returns>
 private string ConvertExpression(LiteralExpressionSyntax condition, List <string> localDeclarationStatements)
 {
     if (!IsLocalDeclarationStatement(condition, localDeclarationStatements))
     {
         return("this." + condition.ToString());
     }
     return(condition.ToString());
 }
Beispiel #3
0
 public override void VisitLiteralExpression(LiteralExpressionSyntax node)
 {
     if (node.Kind() == SyntaxKind.StringLiteralExpression)
     {
         cb.Append("std::string(").Append(node.ToString()).Append(")");
     }
     else
     {
         cb.Append(node.ToString());
     }
 }
        public static string LiteralExpression(LiteralExpressionSyntax expression)
        {
            var r = "";

            switch (expression.Kind())
            {
            //Swift doesn't use the same 'c' character literal syntax, instead you create a String and type annotate it as a Character
            case SyntaxKind.CharacterLiteralExpression:
                //this is sketch, probably shouldn't use char literals o.o
                r = '"' + expression.Token.ValueText.Replace("\\'", "'").Replace("\"", "\\\"") + '"';
                break;

            case SyntaxKind.NullKeyword:
            case SyntaxKind.NullLiteralExpression:
                switch (Builder.Instance.Language)
                {
                case Languages.Swift:
                    r = "nil";
                    break;

                case Languages.Kotlin:
                    r = "null";
                    break;

                case Languages.TypeScript:
                    r = "null";
                    break;

                case Languages.Php:
                    r = "null";
                    break;
                }

                break;

            case SyntaxKind.StringLiteralExpression:
                r = Builder.Instance.LanguageConvertLiteralExpressionString(expression.ToString());
                break;

            default:
                r = expression.ToString();
                break;
            }

            r = expression.ToFullString().Replace(expression.ToString(), r);

            return(r);
        }
Beispiel #5
0
		public static void Go(HaxeWriter writer, LiteralExpressionSyntax expression)
		{
			var str = expression.ToString();

			if (str.StartsWith("@"))
				str = "\"" + str.RemoveFromStartOfString("@\"").RemoveFromEndOfString("\"").Replace("\\", "\\\\").Replace("\"\"", "\\\"") + "\"";
			
			if (str.StartsWith("'") && str.EndsWith("'"))
			{
				//chars just get written as integers

				str = str.Substring(1, str.Length - 2);

				if (str.StartsWith("\\"))
					str = str.Substring(1);

				if (str.Length != 1)
					throw new Exception("Unexpected char string: " + str);
				str = ((int)str[0]).ToString();
			}

			if (str.EndsWith("f") && !str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
				str = str.Substring(0, str.Length - 1);


			writer.Write(str);
		}
        private LiteralExpression convertLiteralExpressionValue(LiteralExpressionSyntax literalExpressionSyntax)
        {
            var le  = new LiteralExpression();
            var str = literalExpressionSyntax.ToString();

            int    i;
            double d;

            if (int.TryParse(str, out i))
            {
                le.LiteralValue = i;
                le.LiteType     = TypeReference.Parse("int");
            }
            else if (double.TryParse(str, out d))
            {
                le.LiteralValue = d;
                le.LiteType     = TypeReference.Parse("double");
            }
            else
            {
                le.LiteralValue = str;
                le.LiteType     = TypeReference.Parse("string");
            }


            return(le);
        }
Beispiel #7
0
        public static void Go(HaxeWriter writer, LiteralExpressionSyntax expression)
        {
            var str = expression.ToString();

            if (str.StartsWith("@"))
            {
                str = "\"" + str.RemoveFromStartOfString("@\"").RemoveFromEndOfString("\"").Replace("\\", "\\\\").Replace("\"\"", "\\\"") + "\"";
            }

            if (expression.Token.Kind() == SyntaxKind.CharacterLiteralToken)
            {
                //chars just get written as integers

                str = ((int)(char)expression.Token.Value).ToString();
            }

            if (str.EndsWith("f") && !str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                str = str.Substring(0, str.Length - 1);
            }

            if (str.EndsWith("L"))
            {
                str = str.Substring(0, str.Length - 1);
            }


            writer.Write(str);
        }
        public override SyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node)
        {
            if (node.IsKind(SyntaxKind.StringLiteralExpression) &&
                node.ToString().IndexOf('\n') >= 0)
            {
                node = node.WithAdditionalAnnotations(LayoutAnnotations.MultiLineConstructAnnotation);
            }

            return(base.VisitLiteralExpression(node));
        }
        public override SyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node)
        {
            if (node.IsKind(SyntaxKind.StringLiteralExpression)
                && node.ToString().IndexOf('\n') >= 0)
            {
                node = node.WithAdditionalAnnotations(LayoutAnnotations.MultiLineConstructAnnotation);
            }

            return base.VisitLiteralExpression(node);
        }
Beispiel #10
0
        public static string LiteralExpression(LiteralExpressionSyntax node)
        {
            switch (node.CSharpKind())
            {
            case SyntaxKind.CharacterLiteralExpression:
                //this is sketch, probably shouldn't use char literals o.o
                return('"' + node.Token.ValueText.Replace("\\'", "'").Replace("\"", "\\\"") + '"');

            default:
                return(node.ToString());
            }
        }
Beispiel #11
0
        public static void Go(ScalaWriter writer, LiteralExpressionSyntax expression, bool isConst)
        {
            var str = expression.ToString();

            if (str.StartsWith("@"))
            {
                str = "\"" + str.RemoveFromStartOfString("@\"").RemoveFromEndOfString("\"").Replace("\\", "\\\\").Replace("\"\"", "\\\"").Replace("\n", "\\n").Replace("\r", "") + "\"";
            }


            if (str.Length > 65000)
            {
                //Big strings have to be broken up, scala can't render big string constants, even when concatenated.  So we have to pass them to a function to concat at runtime
                writer.Write("System.CsScala.JoinConstants(");
                var raw = str.RemoveFromStartOfString("\"").RemoveFromEndOfString("\"");

                var subLength = 65000;
                for (int i = 0; i < raw.Length; i += subLength)
                {
                    var sub = raw.SubstringSafe(i, subLength);
                    //Make sure we never break in the middle of a backslash sequence.  TODO: This assumes backslash sequences are only ever two characters long, we could break on longer ones.
                    if (sub[sub.Length - 1] == '\\' && sub[sub.Length - 2] != '\\')
                    {
                        sub += raw[i + subLength];
                        i++;
                    }

                    writer.Write("\"");
                    writer.Write(sub);
                    writer.Write("\"");
                    if (i + subLength < raw.Length)
                    {
                        writer.Write(", ");
                    }
                }
                writer.Write(")");
            }
            else
            {
                writer.Write(str);
            }

            var typeInfo = Program.GetModel(expression).GetTypeInfo(expression);

            if (typeInfo.Type != null && typeInfo.ConvertedType != null)
            {
                if (isConst == false && typeInfo.ConvertedType.SpecialType == SpecialType.System_Byte && typeInfo.Type.SpecialType == SpecialType.System_Int32)
                {
                    writer.Write(".toByte");
                }
            }
        }
        public static string LiteralExpression(LiteralExpressionSyntax expression)
        {
            switch (expression.CSharpKind())
            {
            //Swift doesn't use the same 'c' character literal syntax, instead you create a String and type annotate it as a Character
            case SyntaxKind.CharacterLiteralExpression:
                //this is sketch, probably shouldn't use char literals o.o
                return('"' + expression.Token.ValueText.Replace("\\'", "'").Replace("\"", "\\\"") + '"');

            default:
                return(expression.ToString());
            }
        }
Beispiel #13
0
            public override int VisitLiteralExpression(LiteralExpressionSyntax node)
            {
                if (node.Kind() != SyntaxKind.NumericLiteralExpression)
                {
                    throw new InvalidOperationException($"Invalid literal type: {node}");
                }

                var value = node.ToString();

                if (value.StartsWith("0x"))
                {
                    return(Convert.ToInt32(value.Substring(2), 16));
                }

                return(int.Parse(value));
            }
        public static void SetAnnotations(List <VariableDeclarationStatementSyntax> annotations)
        {
            if (annotations == null || !_varValid)
            {
                return;
            }
            _activeVar.Annotations = new Dictionary <string, string>();
            foreach (VariableDeclarationStatementSyntax vdsSyntax in annotations)
            {
                SeparatedSyntaxList <VariableDeclaratorSyntax> sSyntaxList = vdsSyntax.Declaration.Variables;
                if (sSyntaxList.Count != 1)
                {
                    _varValid = false;
                    return;
                }
                VariableDeclaratorSyntax vdSyntax = sSyntaxList[0];
                string key = vdSyntax.Identifier.ValueText;
                EqualsValueClauseSyntax evcSyntax = (EqualsValueClauseSyntax)vdSyntax.Initializer;

                string value = "";
                if (evcSyntax.Value is StringLiteralExpressionSyntax)
                {
                    StringLiteralExpressionSyntax sleSyntax = (StringLiteralExpressionSyntax)evcSyntax.Value;
                    List <SyntaxToken>            tokens    = sleSyntax.Tokens;
                    if (tokens.Count > 0)
                    {
                        value = tokens[0].ValueText;
                    }
                }
                else if (evcSyntax.Value is PrefixUnaryExpressionSyntax)
                {
                    PrefixUnaryExpressionSyntax ueSyntax = (PrefixUnaryExpressionSyntax)evcSyntax.Value;
                    value = ueSyntax.ToString();
                }
                else if (evcSyntax.Value is LiteralExpressionSyntax)
                {
                    LiteralExpressionSyntax ueSyntax = (LiteralExpressionSyntax)evcSyntax.Value;
                    value = ueSyntax.ToString();
                }
                else
                {
                    throw new Exception("Unsupported annontation");
                }

                _activeVar.Annotations.Add(key, value);
            }
        }
        public static string GetLiteral(this ExpressionSyntax expression, SemanticModel semanticModel)
        {
            Contract.Requires(expression != null);
            Contract.Requires(semanticModel != null);

            if (expression is LiteralExpressionSyntax)
            {
                return(expression.ToString());
            }

            IdentifierNameSyntax identifier = expression as IdentifierNameSyntax;

            if (identifier != null)
            {
                var referencedIdentifier = semanticModel.GetSymbolInfo(identifier);
                if (referencedIdentifier.Symbol != null)
                {
                    IFieldSymbol fieldReference = referencedIdentifier.Symbol as IFieldSymbol;
                    if (fieldReference == null)
                    {
                        ILocalSymbol localSymbol = referencedIdentifier.Symbol as ILocalSymbol;
                        return(localSymbol?.ConstantValue?.ToString());
                    }

                    // Checking if the field is a constant
                    string value = fieldReference.ConstantValue?.ToString();
                    if (value != null)
                    {
                        return(value);
                    }

                    // Checking if the field is static readonly with literal initializer
                    if (fieldReference.IsStatic && fieldReference.IsReadOnly)
                    {
                        var referencedSyntax = fieldReference.DeclaringSyntaxReferences.FirstOrDefault();
                        VariableDeclaratorSyntax declarator = referencedSyntax?.GetSyntax() as VariableDeclaratorSyntax;
                        LiteralExpressionSyntax  literal    = declarator?.Initializer.Value as LiteralExpressionSyntax;
                        if (literal != null)
                        {
                            return(literal.ToString());
                        }
                    }
                }
            }

            return(null);
        }
Beispiel #16
0
 public override void VisitLiteralExpression(LiteralExpressionSyntax node)
 {
     switch (node.Kind())
     {
     case SyntaxKind.NumericLiteralExpression:
         var v = decimal.Parse(node.ToString(), CultureInfo.InvariantCulture);
         if (_TupleValues == null)
         {
             Values.Push(new BidAsk(v));
         }
         else
         {
             _TupleValues.Push(v);
         }
         break;
     }
 }
        public override Tristate VisitLiteralExpression(LiteralExpressionSyntax node)
        {
            Tristate state;

            if (_symbolStates.TryGetValue(node.ToString(), out state))
            {
                return(state);
            }

            switch (node.Kind())
            {
            case SyntaxKind.TrueLiteralExpression:
                return(Tristate.True);

            case SyntaxKind.FalseLiteralExpression:
                return(Tristate.False);

            default:
                throw new InvalidPreprocessorExpressionException("Expected true or false literal expression");
            }
        }
Beispiel #18
0
        public static void Go(ScalaWriter writer, LiteralExpressionSyntax expression, bool isConst)
        {
            var str = expression.ToString();

            if (str.StartsWith("@"))
            {
                str = "\"" + str.RemoveFromStartOfString("@\"").RemoveFromEndOfString("\"").Replace("\\", "\\\\").Replace("\"\"", "\\\"").Replace("\r\n", "\\n") + "\"";
            }

            var typeInfo = Program.GetModel(expression).GetTypeInfo(expression);


            writer.Write(str);

            if (typeInfo.Type != null && typeInfo.ConvertedType != null)
            {
                if (isConst == false && typeInfo.ConvertedType.SpecialType == SpecialType.System_Byte && typeInfo.Type.SpecialType == SpecialType.System_Int32)
                {
                    writer.Write(".toByte");
                }
            }
        }
        public static void Go(OutputWriter writer, LiteralExpressionSyntax expression, bool isConst)
        {
            var str = expression.ToString();

            if (str.StartsWith("@"))
            {
                str = "\"" +
                      str.RemoveFromStartOfString("@\"")
                      .RemoveFromEndOfString("\"")
                      .Replace("\\", "\\\\")
                      .Replace("\"\"", "\\\"")
                      .Replace("\r\n", "\\n") + "\"";
            }

            var typeInfo = TypeProcessor.GetTypeInfo(expression);
            var type     = typeInfo.Type;

            if (type == null)
            {
                type = typeInfo.ConvertedType;
            }

            if (type != null && type.SpecialType == SpecialType.System_String)
            {
                writer.Write("_S(" + str + ")");
            }
            else
            {
                writer.Write(str);
            }

            //TODO: will handle these separately
//            if (typeInfo.Type != null && typeInfo.ConvertedType != null)
//            {
//                if (isConst == false && typeInfo.ConvertedType.SpecialType ==SpecialType.System_Byte && typeInfo.Type.SpecialType == SpecialType.System_Int32)
//                    writer.Write(".toByte");
//            }
        }
 private static bool IsNoCandidateDiagnostic(LiteralExpressionSyntax literal)
 {
     return literal.ToString() != "\"\"" ||
            literal.Ancestors().OfType<AttributeArgumentSyntax>().Any() ||
            literal.Ancestors().OfType<ParameterListSyntax>().Any();
 }
Beispiel #21
0
 private static bool IsNoCandidateDiagnostic(LiteralExpressionSyntax literal)
 {
     return(literal.ToString() != "\"\"" ||
            literal.Ancestors().OfType <AttributeArgumentSyntax>().Any() ||
            literal.Ancestors().OfType <ParameterListSyntax>().Any());
 }
Beispiel #22
0
 public static bool Qualifies(LiteralExpressionSyntax node) =>
 EnvironmentVariableInterpolation.Qualifies(node.ToString());
Beispiel #23
0
 public override void VisitLiteralExpression(LiteralExpressionSyntax node)
 {
     if (node.Kind() == SyntaxKind.StringLiteralExpression)
     cb.Append("std::string(").Append(node.ToString()).Append(")");
       else
     cb.Append(node.ToString());
 }
        public static void Go(OutputWriter writer, LiteralExpressionSyntax expression, bool isConst, bool inSwitch = false)
        {
            var str = expression.ToString();


            if (str.Trim() == "null")
            {
                writer.Write("null");
                return;
            }

            if (str.StartsWith("@\""))
            {
                str = "r" + FixUpLiterals(EncodeNonAsciiCharacters(FixUpLiterals(str.Substring(1))));

                /*str = "\"" +
                 *    str.RemoveFromStartOfString("@\"")
                 *        .RemoveFromEndOfString("\"")
                 *        .Replace("\\", "\\\\")
                 *        .Replace("\"\"", "\\\"")
                 *        .Replace("\r\n", "\\n") + "\"";*/
            }

            var typeInfo = TypeProcessor.GetTypeInfo(expression);
            var type     = typeInfo.Type;

            if (type == null)
            {
                type = typeInfo.ConvertedType;
            }



            if (type != null && type.SpecialType == SpecialType.System_String)
            {
                if (str.Contains("\\u") || str.Contains("\\x"))
                {
                    str = FixUpLiterals(EncodeNonAsciiCharacters(FixUpLiterals(str)));
                }
                if (str == "null")
                {
                    if (inSwitch)
                    {
                        writer.Write("-1");
                    }
                    else
                    {
                        writer.Write("null");
                    }
                }
                else if (inSwitch)
                {
                    writer.Write(str);
                }
                else
                {
                }
                writer.Write("_S(" + str + ")");
            }
            else if (type != null && type.Name == "Nullable")//Nullable Support
            {
                var atype = TypeProcessor.ConvertType(type);
                writer.Write(atype + "()");
            }
            else
            {
                if (type.SpecialType == SpecialType.System_Boolean)
                {
                    writer.Write(str);
                }
                else if (type.SpecialType == SpecialType.System_Char)
                {
                    if (str.Contains("\\u") || str.Contains("\\x"))
                    {
                        writer.Write("cast(wchar)" + FixUpCharacterLiteral(str));
                    }
                    else
                    {
                        writer.Write(str);
                    }
                }
                else
                {
                    //No need to convert these ... lets just put the correct suffix ourselves


                    if (typeInfo.ConvertedType != typeInfo.Type && typeInfo.ConvertedType.IsPrimitiveInteger() && typeInfo.Type.IsPrimitiveInteger())
                    {
                        writer.Write("cast({0})", TypeProcessor.ConvertType(typeInfo.ConvertedType)); //TODO: add better, less clumsy conversion
                    }

//                    //Number literals //TODO: make these convert to D Literal Suffixes
//                    var suffix = realTypeSuffixes.FirstOrDefault (j => str.EndsWith (j));
//                    if (suffix != null)
//						str = str.Replace(suffix,drealTypeSuffixes[Array.IndexOf(realTypeSuffixes,suffix)]);
//					else
//					{
//						suffix = integerTypeSuffixes.FirstOrDefault (j => str.EndsWith (j));
//						if (suffix != null)
//							str = str.Replace(suffix,dintegerTypeSuffixes[Array.IndexOf(integerTypeSuffixes,suffix)]);
//					}

                    writer.Write(str);
                }
            }
        }
        private async Task <Document> ReplaceStringWithLocalizerFormat(Document document, LiteralExpressionSyntax litDecl, CancellationToken cancellationToken)
        {
            try
            {
                //Get the details of the ID to use
                currentProject = ProjectsManager.projects[document.Project.Name];
                newIDKey       = currentProject.LocalizerSettings.NextTag;
                newValue       = litDecl.ToString();

                if (newValue.StartsWith("\""))
                {
                    newValue = newValue.Substring(1);
                }
                if (newValue.EndsWith("\""))
                {
                    newValue = newValue.Substring(0, newValue.Length - 1);
                }

                //Get the document
                var root = await document.GetSyntaxRootAsync(cancellationToken);

                CompilationUnitSyntax newroot = (CompilationUnitSyntax)root;

                SyntaxNode replacedNode;
                try
                {
                    //Set up the call to Localizer.Format
                    IdentifierNameSyntax         localizer    = SyntaxFactory.IdentifierName("Localizer");
                    IdentifierNameSyntax         format       = SyntaxFactory.IdentifierName("Format");
                    MemberAccessExpressionSyntax memberaccess = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, localizer, format);

                    ArgumentSyntax arg = SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(newIDKey)));
                    SeparatedSyntaxList <ArgumentSyntax> argList = SyntaxFactory.SeparatedList(new[] { arg });

                    SyntaxAnnotation syntaxAnnotation = new SyntaxAnnotation("LocalizerFormat");

                    SyntaxNode writecall =
                        SyntaxFactory.InvocationExpression(memberaccess,
                                                           SyntaxFactory.ArgumentList(argList)

                                                           ).WithAdditionalAnnotations(syntaxAnnotation).WithTriviaFrom(litDecl);


                    newroot = newroot.ReplaceNode(litDecl, (SyntaxNode)writecall);

                    //get the changed node back from teh updated document root
                    replacedNode = newroot.GetAnnotatedNodes(syntaxAnnotation).Single();
                }
                catch (Exception ex)
                {
                    OutputManager.WriteErrorEx(ex, "Unable to compile the Localizer call. Refactor cancelled.");
                    return(null);
                }

                try
                {
                    //find the Trivial that marks the end of this line
                    bool         foundEOL   = false;
                    SyntaxNode   objToCheck = replacedNode;
                    SyntaxTrivia objEOL     = SyntaxFactory.Comment(" ");

                    //This look works upwards through the structure by parent to get bigger bits of the
                    // syntax tree to find the first EOL after the replaced Node
                    while (!foundEOL)
                    {
                        //Go up one level
                        objToCheck = objToCheck.Parent;

                        //If we found it get out
                        if (FindEOLAfter(objToCheck, replacedNode.FullSpan.End, ref objEOL))
                        {
                            foundEOL = true;
                        }

                        //If we just checked the whole document then stop looping
                        if (objToCheck == root)
                        {
                            break;
                        }
                    }

                    //If we found the EOL Trivia then insert the new comment before it
                    if (foundEOL)
                    {
                        var tabs    = SyntaxFactory.Whitespace("\t\t");
                        var comment = SyntaxFactory.Comment("// " + newIDKey + " = " + newValue);
                        List <SyntaxTrivia> lineComment = new List <SyntaxTrivia>();
                        lineComment.Add(tabs);
                        lineComment.Add(comment);

                        newroot = newroot.InsertTriviaBefore(objEOL, lineComment);
                    }
                }
                catch (Exception ex)
                {
                    OutputManager.WriteErrorEx(ex, "Unable to add comment to end of line. Add it manually if you like.");
                }


                try {
                    //Make sure the file has a usings so the short name works
                    if (!newroot.Usings.Any(u => u.Name.GetText().ToString() == "KSP.Localization"))
                    {
                        newroot = newroot.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("KSP"), SyntaxFactory.IdentifierName("Localization"))));
                    }
                }
                catch (Exception ex)
                {
                    OutputManager.WriteErrorEx(ex, "Unable to add usings line to head of file. Add it manually.");
                }

                //Now convert it to the document to send it back
                try
                {
                    var result = document.WithSyntaxRoot(newroot);

                    return(result);
                }
                catch (Exception ex)
                {
                    OutputManager.WriteErrorEx(ex, "Unable to rewrite the document. Refactor cancelled.");
                    return(null);
                }
            }
            catch (Exception ex)
            {
                OutputManager.WriteErrorEx(ex, "General error refactoring the token. Refactor cancelled.");
            }

            return(null);
        }
 public static string LiteralExpression(LiteralExpressionSyntax expression)
 {
     switch (expression.CSharpKind())
     {
         //Swift doesn't use the same 'c' character literal syntax, instead you create a String and type annotate it as a Character
         case SyntaxKind.CharacterLiteralExpression:
             //this is sketch, probably shouldn't use char literals o.o
             return '"' + expression.Token.ValueText.Replace("\\'", "'").Replace("\"", "\\\"") + '"';
         default:
             return expression.ToString();
     }
 }
 public LiteralMessage(LiteralExpressionSyntax originalExpression)
     : base(originalExpression)
 {
     Contract.Requires(originalExpression != null);
     Literal = originalExpression.ToString();
 }
Beispiel #28
0
        public override void VisitLiteralExpression(LiteralExpressionSyntax node)
        {
            switch (node.Kind())
            {
            case SyntaxKind.NullLiteralExpression:
                AddCilInstruction(ilVar, OpCodes.Ldnull);
                break;

            case SyntaxKind.StringLiteralExpression:
                AddCilInstruction(ilVar, OpCodes.Ldstr, node.ToFullString());
                break;

            case SyntaxKind.CharacterLiteralExpression:
            case SyntaxKind.NumericLiteralExpression:
                AddLocalVariableAndHandleCallOnValueTypeLiterals(node, "assembly.MainModule.TypeSystem.Int32", node.ToString());
                break;

            case SyntaxKind.TrueLiteralExpression:
            case SyntaxKind.FalseLiteralExpression:
                AddLocalVariableAndHandleCallOnValueTypeLiterals(node, "assembly.MainModule.TypeSystem.Boolean", bool.Parse(node.ToString()) ? 1 : 0);
                break;

            default:
                throw new ArgumentException($"Literal ( {node}) of type {node.Kind()} not supported yet.");
            }

            void AddLocalVariableAndHandleCallOnValueTypeLiterals(LiteralExpressionSyntax literalNode, string cecilTypeSystemReference, object literalValue)
            {
                AddCilInstruction(ilVar, LoadOpCodeFor(literalNode), literalValue);
                var localVarParent = (CSharpSyntaxNode)literalNode.Parent;

                if (localVarParent.Accept(new UsageVisitor()) == UsageKind.CallTarget)
                {
                    var tempLocalName = MethodExtensions.LocalVariableNameFor("tmp_", "tmp_".UniqueId().ToString());
                    AddCecilExpression("var {0} = new VariableDefinition({1});", tempLocalName, cecilTypeSystemReference);
                    AddCecilExpression("{0}.Body.Variables.Add({1});", Context.DefinitionVariables.GetLastOf(MemberKind.Method).VariableName, tempLocalName);

                    AddCilInstruction(ilVar, OpCodes.Stloc, $"{tempLocalName}");
                    AddCilInstruction(ilVar, OpCodes.Ldloca_S, $"{tempLocalName}");
                }
            }
        }
        public override SyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node)
        {
            var kind = node.Kind();

            if ((kind != SyntaxKind.NumericLiteralExpression) &&
                (kind != SyntaxKind.StringLiteralExpression) &&
                (kind != SyntaxKind.FalseLiteralExpression) &&
                (kind != SyntaxKind.TrueLiteralExpression) &&
                (kind != SyntaxKind.CharacterLiteralExpression)
                )
            {
                return(node);
            }

            CheckCastContex(node);

            string      value        = node.ToString();
            bool        found        = false;
            VirtualData constant     = null;
            string      requiredType = GetRequiredType(node); //in the case of return statements

            if (requiredType.Equals("void"))
            {
                requiredType = ""; // return statement was added as a refactoring "hack"
            }
            var typeInfo     = _virtualizationContext.semanticModel.GetTypeInfo(node);
            var declaredType = typeInfo.Type.ToString();

            foreach (var data in _virtualizationContext.data)
            {
                if (value.Equals(data.Name))
                {
                    if (requiredType.Equals("") && declaredType.Equals(data.Type))
                    {
                        found        = true;
                        constant     = data;
                        requiredType = declaredType;
                        break;
                    }
                    if (requiredType.Equals(data.Type))
                    {
                        found    = true;
                        constant = data;
                        break;
                    }
                }
            }
            if (!found)
            {
                if (requiredType.Equals(""))
                {
                    requiredType = declaredType;
                }

                int              index           = _virtualizationContext.DataIndex;
                string           name            = value;
                SyntaxAnnotation dataIndexMarker = new SyntaxAnnotation("index", index + "");
                SyntaxAnnotation nameMarker      = new SyntaxAnnotation("name", name);
                SyntaxAnnotation constantMarker  = new SyntaxAnnotation("type", "constant");
                SyntaxAnnotation codeIndexMarker = new SyntaxAnnotation("code", "undefined");
                SyntaxAnnotation uniqueMarker    = new SyntaxAnnotation("unique", "" + VirtualizationContext.UniqueId);

                constant       = new VirtualData();
                constant.Index = index;
                constant.Name  = name;
                var info = requiredType;

                constant.Type         = info;
                constant.Node         = node;
                constant.DefaultValue = node;
                constant.Annotations.Add(dataIndexMarker);
                constant.Annotations.Add(nameMarker);
                constant.Annotations.Add(constantMarker);
                constant.Annotations.Add(codeIndexMarker);
                constant.Annotations.Add(uniqueMarker);
                _virtualizationContext.data.Add(constant);
            }



            ExpressionSyntax newNode = SyntaxFactoryExtensions.DataCodeVirtualAccess();

            newNode = newNode.WithAdditionalAnnotations(constant.Annotations);
            ExpressionSyntax newExpression;

            if (CastEnabled)
            {
                newExpression = SyntaxFactory.CastExpression(SyntaxFactory.IdentifierName
                                                             (
                                                                 @"" + constant.Type
                                                             ),
                                                             newNode
                                                             );
            }
            else
            {
                newExpression = newNode;
            }

            //TODO: add annotations + comments
            newExpression = newExpression.WithLeadingTrivia(node.GetLeadingTrivia())
                            .WithTrailingTrivia(node.GetTrailingTrivia())
            ;

            return(newExpression);
        }
		public static void Go(OutputWriter writer, LiteralExpressionSyntax expression, bool isConst, bool inSwitch=false)
        {
            var str = expression.ToString();


            if (str.Trim() == "null")
            {
                writer.Write("null");
                return;
            }

            if (str.StartsWith("@\""))
            {
                str = "r" + FixUpLiterals(EncodeNonAsciiCharacters(FixUpLiterals(str.Substring(1))));
                /*str = "\"" +
                      str.RemoveFromStartOfString("@\"")
                          .RemoveFromEndOfString("\"")
                          .Replace("\\", "\\\\")
                          .Replace("\"\"", "\\\"")
                          .Replace("\r\n", "\\n") + "\"";*/
            }

            var typeInfo = TypeProcessor.GetTypeInfo(expression);
            var type = typeInfo.Type;
            if (type == null)
                type = typeInfo.ConvertedType;

         

            if (type != null && type.SpecialType == SpecialType.System_String)
            {
                if (str.Contains("\\u") || str.Contains("\\x"))
               
                str = FixUpLiterals(EncodeNonAsciiCharacters(FixUpLiterals(str)));
                if (str == "null")
                {
                    if (inSwitch)
                        writer.Write("-1");
                    else
                        writer.Write("null");
                }
                else if (inSwitch)
                {
                    writer.Write(str);
                }
                else
                {
                }
                writer.Write("_S(" + str + ")");
            }
            else if (type != null && type.Name == "Nullable")//Nullable Support
            {
               
                var atype = TypeProcessor.ConvertType(type);
                writer.Write(atype + "()");
                
            }
            else
            {
                if(type.SpecialType==SpecialType.System_Boolean)
                    writer.Write(str);
                else if (type.SpecialType == SpecialType.System_Char)
                {

if(str.Contains("\\u") || str.Contains("\\x"))
                    writer.Write("cast(wchar)"+FixUpCharacterLiteral(str));
else
{
    writer.Write(str);
}
                }
                else
                {

                    //No need to convert these ... lets just put the correct suffix ourselves


                    if (typeInfo.ConvertedType != typeInfo.Type && typeInfo.ConvertedType.IsPrimitiveInteger() && typeInfo.Type.IsPrimitiveInteger())
                    {
                        writer.Write("cast({0})",TypeProcessor.ConvertType(typeInfo.ConvertedType)); //TODO: add better, less clumsy conversion
                    }

//                    //Number literals //TODO: make these convert to D Literal Suffixes
//                    var suffix = realTypeSuffixes.FirstOrDefault (j => str.EndsWith (j));
//                    if (suffix != null)
//						str = str.Replace(suffix,drealTypeSuffixes[Array.IndexOf(realTypeSuffixes,suffix)]);
//					else
//					{
//						suffix = integerTypeSuffixes.FirstOrDefault (j => str.EndsWith (j));
//						if (suffix != null)
//							str = str.Replace(suffix,dintegerTypeSuffixes[Array.IndexOf(integerTypeSuffixes,suffix)]);
//					}

                    writer.Write(str);
                }
            }


        }
Beispiel #31
0
 public override void VisitLiteralExpression(LiteralExpressionSyntax node)
 {
     Value = node.ToString();
     base.VisitLiteralExpression(node);
 }