public string AddLocal(string name, AstType type) { this.Emitter.Locals.Add(name, type); name = name.StartsWith(Bridge.Translator.Emitter.FIX_ARGUMENT_NAME) ? name.Substring(Bridge.Translator.Emitter.FIX_ARGUMENT_NAME.Length) : name; string vName = name; if (Helpers.IsReservedWord(name)) { vName = this.GetUniqueName(name); } if (!this.Emitter.LocalsNamesMap.ContainsKey(name)) { this.Emitter.LocalsNamesMap.Add(name, vName); } else { this.Emitter.LocalsNamesMap[name] = this.GetUniqueName(vName); } var result = this.Emitter.LocalsNamesMap[name]; if (this.Emitter.IsAsync && !this.Emitter.AsyncVariables.Contains(result)) { this.Emitter.AsyncVariables.Add(result); } return result; }
void AddTypeArguments (ATypeNameExpression texpr, AstType result) { if (!texpr.HasTypeArguments) return; foreach (var arg in texpr.TypeArguments.Args) { result.AddChild (ConvertToType (arg), AstType.Roles.TypeArgument); } }
public static object GetDefaultFieldValue(AstType type, IMemberResolver resolver) { if (type is PrimitiveType) { var primitiveType = (PrimitiveType)type; switch (primitiveType.KnownTypeCode) { case KnownTypeCode.Decimal: return 0m; case KnownTypeCode.Int16: case KnownTypeCode.Int32: case KnownTypeCode.Int64: case KnownTypeCode.UInt16: case KnownTypeCode.UInt32: case KnownTypeCode.UInt64: case KnownTypeCode.Byte: case KnownTypeCode.Double: case KnownTypeCode.SByte: case KnownTypeCode.Single: return 0; case KnownTypeCode.Boolean: return false; } } var resolveResult = resolver.ResolveNode(type, null); var o = GetDefaultFieldValue(resolveResult.Type, false); if (o != null) { return o; } if (!resolveResult.IsError && NullableType.IsNullable(resolveResult.Type)) { return null; } if (!resolveResult.IsError && resolveResult.Type.IsKnownType(KnownTypeCode.Enum)) { return 0; } if (!resolveResult.IsError && resolveResult.Type.Kind == TypeKind.Struct) { return type; } return null; }
protected FieldDeclaration GetFieldDeclaration(String name, AstType propertyType) { var declaration = new FieldDeclaration(); declaration.Name = name; declaration.Modifiers = Modifiers.Public; declaration.ReturnType = propertyType; IDELogger.Log("BaseRefactoringDialog::GetFieldDeclaration -- {0}", declaration.Name); return declaration; }
static VariableDeclarationStatement GetVariableDeclarationStatement (RefactoringContext context, out AstType resolvedType) { var result = context.GetNode<VariableDeclarationStatement> (); if (result != null && result.Variables.Count == 1 && !result.Variables.First ().Initializer.IsNull && result.Variables.First ().NameToken.Contains (context.Location.Line, context.Location.Column)) { resolvedType = context.ResolveType (result.Variables.First ().Initializer); if (resolvedType == null) return null; return result; } resolvedType = null; return null; }
static VariableDeclarationStatement GetVariableDeclarationStatement (RefactoringContext context, out AstType resolvedType, CancellationToken cancellationToken = default(CancellationToken)) { var result = context.GetNode<VariableDeclarationStatement> (); if (result != null && result.Variables.Count == 1 && !result.Variables.First ().Initializer.IsNull && result.Variables.First ().NameToken.Contains (context.Location.Line, context.Location.Column)) { resolvedType = result.Type.Clone (); // resolvedType = context.Resolve (result.Variables.First ().Initializer).Type.ConvertToAstType (); // if (resolvedType == null) // return null; return result; } resolvedType = null; return null; }
static VariableDeclarationStatement GetVariableDeclarationStatement(RefactoringContext context, out AstType resolvedType, CancellationToken cancellationToken = default(CancellationToken)) { var result = context.GetNode<VariableDeclarationStatement> (); if (result != null && result.Variables.Count == 1 && !result.Variables.First ().Initializer.IsNull && result.Variables.First ().NameToken.Contains (context.Location.Line, context.Location.Column)) { var type = context.Resolve(result.Variables.First ().Initializer).Type; if (type.Equals(SpecialType.NullType) || type.Equals(SpecialType.UnknownType)) { resolvedType = new PrimitiveType ("object"); } else { resolvedType = context.CreateShortType (type); } return result; } resolvedType = null; return null; }
static VariableInitializer GetVariableDeclarationStatement (RefactoringContext context, out AstType resolvedType, CancellationToken cancellationToken = default(CancellationToken)) { var result = context.GetNode<VariableInitializer> (); if (result != null && !result.Initializer.IsNull && context.Location <= result.Initializer.StartLocation) { var type = context.Resolve(result).Type; if (type.Equals(SpecialType.NullType) || type.Equals(SpecialType.UnknownType)) { resolvedType = new PrimitiveType ("object"); } else { resolvedType = context.CreateShortType (type); } return result; } resolvedType = null; return null; }
Expression GetDefaultValueExpression (AstType astType) { var type = ctx.ResolveType (astType); if ((type.IsReferenceType ?? false) || type.Kind == TypeKind.Dynamic) return new NullReferenceExpression (); var typeDefinition = type.GetDefinition (); if (typeDefinition != null) { switch (typeDefinition.KnownTypeCode) { case KnownTypeCode.Boolean: return new PrimitiveExpression (false); case KnownTypeCode.Char: return new PrimitiveExpression ('\0'); case KnownTypeCode.SByte: case KnownTypeCode.Byte: case KnownTypeCode.Int16: case KnownTypeCode.UInt16: case KnownTypeCode.Int32: return new PrimitiveExpression (0); case KnownTypeCode.Int64: return new Choice { new PrimitiveExpression (0), new PrimitiveExpression (0L) }; case KnownTypeCode.UInt32: return new Choice { new PrimitiveExpression (0), new PrimitiveExpression (0U) }; case KnownTypeCode.UInt64: return new Choice { new PrimitiveExpression (0), new PrimitiveExpression (0U), new PrimitiveExpression (0UL) }; case KnownTypeCode.Single: return new Choice { new PrimitiveExpression (0), new PrimitiveExpression (0F) }; case KnownTypeCode.Double: return new Choice { new PrimitiveExpression (0), new PrimitiveExpression (0F), new PrimitiveExpression (0D) }; case KnownTypeCode.Decimal: return new Choice { new PrimitiveExpression (0), new PrimitiveExpression (0M) }; case KnownTypeCode.NullableOfT: return new NullReferenceExpression (); } if (type.Kind == TypeKind.Struct) return new ObjectCreateExpression (astType.Clone ()); } return new DefaultValueExpression (astType.Clone ()); }
void AddTypeArguments (ATypeNameExpression texpr, AstType result) { if (texpr.TypeArguments == null || texpr.TypeArguments.Args == null) return; var loc = LocationsBag.GetLocations (texpr.TypeArguments); if (loc != null && loc.Count >= 2) result.AddChild (new CSharpTokenNode (Convert (loc [loc.Count - 2]), 1), AstType.Roles.LChevron); int i = 0; foreach (var arg in texpr.TypeArguments.Args) { result.AddChild (ConvertToType (arg), AstType.Roles.TypeArgument); if (loc != null && i < loc.Count - 2) result.AddChild (new CSharpTokenNode (Convert (loc [i++]), 1), AstType.Roles.Comma); } if (loc != null && loc.Count >= 2) result.AddChild (new CSharpTokenNode (Convert (loc [loc.Count - 1]), 1), AstType.Roles.RChevron); }
/// <summary> /// Declares a variable in the smallest required scope. /// </summary> /// <param name="node">The root of the subtree being searched for the best insertion position</param> /// <param name="type">The type of the new variable</param> /// <param name="name">The name of the new variable</param> /// <param name="allowPassIntoLoops">Whether the variable is allowed to be placed inside a loop</param> public static VariableDeclarationStatement DeclareVariable(AstNode node, AstType type, string name, bool allowPassIntoLoops = true) { VariableDeclarationStatement result = null; AstNode pos = FindInsertPos(node, name, allowPassIntoLoops); if (pos != null) { Match m = assignmentPattern.Match(pos); if (m != null && m.Get<IdentifierExpression>("ident").Single().Identifier == name) { result = new VariableDeclarationStatement(type, name, m.Get<Expression>("init").Single().Detach()); pos.ReplaceWith(result); } else { result = new VariableDeclarationStatement(type, name); pos.Parent.InsertChildBefore(pos, result, BlockStatement.StatementRole); } } return result; }
public static IEnumerable<string> GenerateNameProposals(AstType type) { if (type is PrimitiveType) { var pt = (PrimitiveType)type; switch (pt.Keyword) { case "object": yield return "o"; yield return "obj"; break; case "bool": yield return "b"; yield return "pred"; break; case "double": case "float": case "decimal": yield return "d"; yield return "f"; yield return "m"; break; case "char": yield return "c"; break; default: yield return "i"; yield return "j"; yield return "k"; break; } yield break; } string name; if (type is SimpleType) { name = ((SimpleType)type).Identifier; } else if (type is MemberType) { name = ((MemberType)type).MemberName; } else { yield break; } var names = WordParser.BreakWords(name); if (names.Count > 0) { names [0] = Char.ToLower(names [0] [0]) + names [0].Substring(1); } yield return string.Join("", names); }
public TypeMetadata(string typeName, string @namespace, string csharpName, string scriptName, IReadOnlyList<string> tagNames, bool generate, bool inherit, TypeKind typeKind, bool includeConstructors, IReadOnlyList<TypeOverride> typeOverrides, AstType aliasFor, IEnumerable<Tuple<string, string>> renames, IEnumerable<string> removes, IReadOnlyList<string> addInDerivedTypes, IReadOnlyList<GeneratedEnum> generatedEnums) { TypeName = typeName; Namespace = @namespace; CSharpName = csharpName; ScriptName = scriptName; TagNames = tagNames.AsReadOnlySafe(); Generate = generate && typeKind != TypeKind.Mixin && typeKind != TypeKind.Skip; Inherit = inherit; TypeKind = typeKind; IncludeConstructors = includeConstructors; TypeOverrides = typeOverrides.AsReadOnlySafe(); AliasFor = aliasFor; Renames = new ReadOnlyDictionary<string, string>((renames ?? new Tuple<string, string>[0]).ToDictionary(x => x.Item1, x => x.Item2)); Removes = removes.AsReadOnlySafe(); AddInDerivedTypes = addInDerivedTypes.AsReadOnlySafe(); GeneratedEnums = generatedEnums.AsReadOnlySafe(); }
protected virtual void EmitTypeReference() { AstType astType = Type; Write(H5Types.ToJsName(astType, Emitter)); }
public IType ResolveType (AstType type) { return resolver.Resolve (type, cancellationToken).Type; }
public TypeBlock(IEmitter emitter, AstType type) : base(emitter, type) { Emitter = emitter; Type = type; }
public static string GetStructDefaultValue(AstType type, IEmitter emitter) { var rr = emitter.Resolver.ResolveNode(type, emitter); return(GetStructDefaultValue(rr.Type, emitter)); }
bool TryConvertAssignmentExpressionIntoVariableDeclaration(Statement declarationPoint, AstType type, string variableName) { // convert the declarationPoint into a VariableDeclarationStatement ExpressionStatement es = declarationPoint as ExpressionStatement; if (es != null) { return(TryConvertAssignmentExpressionIntoVariableDeclaration(es.Expression, type, variableName)); } return(false); }
Expression ConvertTypeIs(InvocationExpression invocation) { if (invocation.Arguments.Count != 2) { return(null); } Expression converted = Convert(invocation.Arguments.ElementAt(0)); AstType type = ConvertTypeReference(invocation.Arguments.ElementAt(1)); if (converted != null && type != null) { return new IsExpression { Expression = converted, Type = type } } ; return(null); } #endregion #region Convert Array Expression ConvertArrayIndex(InvocationExpression invocation) { if (invocation.Arguments.Count != 2) { return(NotSupported(invocation)); } Expression targetConverted = Convert(invocation.Arguments.First()); if (targetConverted == null) { return(null); } Expression index = invocation.Arguments.ElementAt(1); Expression indexConverted = Convert(index); if (indexConverted != null) { return(new IndexerExpression(targetConverted, indexConverted)); } IList <Expression> indexesConverted = ConvertExpressionsArray(index); if (indexesConverted != null) { return(new IndexerExpression(targetConverted, indexesConverted)); } return(null); } Expression ConvertArrayLength(InvocationExpression invocation) { if (invocation.Arguments.Count != 1) { return(NotSupported(invocation)); } Expression targetConverted = Convert(invocation.Arguments.Single()); if (targetConverted != null) { return(targetConverted.Member("Length")); } else { return(null); } } Expression ConvertNewArrayInit(InvocationExpression invocation) { if (invocation.Arguments.Count != 2) { return(NotSupported(invocation)); } AstType elementType = ConvertTypeReference(invocation.Arguments.ElementAt(0)); IList <Expression> elements = ConvertExpressionsArray(invocation.Arguments.ElementAt(1)); if (elementType != null && elements != null) { if (ContainsAnonymousType(elementType)) { elementType = null; } return(new ArrayCreateExpression { Type = elementType, AdditionalArraySpecifiers = { new ArraySpecifier() }, Initializer = new ArrayInitializerExpression(elements) }); } return(null); } Expression ConvertNewArrayBounds(InvocationExpression invocation) { if (invocation.Arguments.Count != 2) { return(NotSupported(invocation)); } AstType elementType = ConvertTypeReference(invocation.Arguments.ElementAt(0)); IList <Expression> arguments = ConvertExpressionsArray(invocation.Arguments.ElementAt(1)); if (elementType != null && arguments != null) { if (ContainsAnonymousType(elementType)) { elementType = null; } ArrayCreateExpression ace = new ArrayCreateExpression(); ace.Type = elementType; ace.Arguments.AddRange(arguments); return(ace); } return(null); } bool ContainsAnonymousType(AstType type) { foreach (AstType t in type.DescendantsAndSelf.OfType <AstType>()) { ITypeDefOrRef tr = t.Annotation <ITypeDefOrRef>(); if (tr != null && tr.IsAnonymousType()) { return(true); } } return(false); } #endregion }
protected virtual void EmitInlineCast(ResolveResult expressionrr, Expression expression, AstType astType, string castCode, bool isCastAttr, string method) { this.Write(""); string name; if (this.InlineMethod == null) { name = "{this}"; } else { name = "{" + this.InlineMethod.Parameters[0].Name + "}"; if (!castCode.Contains(name)) { name = "{this}"; } } string tempVar = null; string expressionStr; var memberTargetrr = expressionrr as MemberResolveResult; bool isField = memberTargetrr != null && memberTargetrr.Member is IField && (memberTargetrr.TargetResult is ThisResolveResult || memberTargetrr.TargetResult is LocalResolveResult); var oldBuilder = this.SaveWriter(); var sb = this.NewWriter(); expression.AcceptVisitor(this.Emitter); expressionStr = sb.ToString(); this.RestoreWriter(oldBuilder); if (!(expressionrr is ThisResolveResult || expressionrr is ConstantResolveResult || expressionrr is LocalResolveResult || isField) && isCastAttr) { tempVar = this.GetTempVarName(); } if (castCode.Contains(name)) { castCode = castCode.Replace(name, tempVar ?? expressionStr); } if (castCode.Contains("{0}")) { oldBuilder = this.SaveWriter(); sb = this.NewWriter(); this.EmitCastType(astType); castCode = castCode.Replace("{0}", sb.ToString()); this.RestoreWriter(oldBuilder); } if (isCastAttr) { if (tempVar != null) { castCode = string.Format("({0} = {1}, Bridge.{2}({0}, {4}({0}) && ({3})))", tempVar, expressionStr, method, castCode, JS.Funcs.BRIDGE_HASVALUE); this.RemoveTempVar(tempVar); } else { castCode = string.Format("Bridge.{1}({0}, {3}({0}) && ({2}))", expressionStr, method, castCode, JS.Funcs.BRIDGE_HASVALUE); } } this.Write(castCode); }
public static bool IsArgList(this AstType type) { var simpleType = type as SimpleType; return(simpleType != null && simpleType.Identifier == "__arglist"); }
static Expression GetDefaultValueExpression(RefactoringContext context, AstType astType) { var type = context.ResolveType(astType); // array if (type.Kind == TypeKind.Array) { return(new ObjectCreateExpression(astType.Clone())); } // enum if (type.Kind == TypeKind.Enum) { var members = type.GetMembers().ToArray(); if (members.Length == 0) { return(new DefaultValueExpression(astType.Clone())); } return(astType.Member(members[0].Name).Clone()); } if ((type.IsReferenceType ?? false) || type.Kind == TypeKind.Dynamic) { return(new NullReferenceExpression()); } var typeDefinition = type.GetDefinition(); if (typeDefinition != null) { switch (typeDefinition.KnownTypeCode) { case KnownTypeCode.Boolean: return(new PrimitiveExpression(false)); case KnownTypeCode.Char: return(new PrimitiveExpression('\0')); case KnownTypeCode.SByte: case KnownTypeCode.Byte: case KnownTypeCode.Int16: case KnownTypeCode.UInt16: case KnownTypeCode.Int32: case KnownTypeCode.UInt32: case KnownTypeCode.Int64: case KnownTypeCode.UInt64: case KnownTypeCode.Single: case KnownTypeCode.Double: case KnownTypeCode.Decimal: return(new PrimitiveExpression(0)); case KnownTypeCode.NullableOfT: return(new NullReferenceExpression()); } if (type.Kind == TypeKind.Struct) { return(new ObjectCreateExpression(astType.Clone())); } } return(new DefaultValueExpression(astType.Clone())); }
Expression GetDefaultValueExpression(AstType astType) { var type = ctx.ResolveType(astType); if ((type.IsReferenceType ?? false) || type.Kind == TypeKind.Dynamic) { return(new NullReferenceExpression()); } var typeDefinition = type.GetDefinition(); if (typeDefinition != null) { switch (typeDefinition.KnownTypeCode) { case KnownTypeCode.Boolean: return(new PrimitiveExpression(false)); case KnownTypeCode.Char: return(new PrimitiveExpression('\0')); case KnownTypeCode.SByte: case KnownTypeCode.Byte: case KnownTypeCode.Int16: case KnownTypeCode.UInt16: case KnownTypeCode.Int32: return(new PrimitiveExpression(0)); case KnownTypeCode.Int64: return(new Choice { new PrimitiveExpression(0), new PrimitiveExpression(0L) }); case KnownTypeCode.UInt32: return(new Choice { new PrimitiveExpression(0), new PrimitiveExpression(0U) }); case KnownTypeCode.UInt64: return(new Choice { new PrimitiveExpression(0), new PrimitiveExpression(0U), new PrimitiveExpression(0UL) }); case KnownTypeCode.Single: return(new Choice { new PrimitiveExpression(0), new PrimitiveExpression(0F) }); case KnownTypeCode.Double: return(new Choice { new PrimitiveExpression(0), new PrimitiveExpression(0F), new PrimitiveExpression(0D) }); case KnownTypeCode.Decimal: return(new Choice { new PrimitiveExpression(0), new PrimitiveExpression(0M) }); case KnownTypeCode.NullableOfT: return(new NullReferenceExpression()); } if (type.Kind == TypeKind.Struct) { return(new ObjectCreateExpression(astType.Clone())); } } return(new DefaultValueExpression(astType.Clone())); }
static MemberReferenceExpression CreateMethodImplReferenceNode(MethodImplOptions option, AstType methodImplOptionsType) { return(new MemberReferenceExpression(methodImplOptionsType.Clone(), Enum.GetName(typeof(MethodImplOptions), option))); }
public AsExpression(Expression expression, AstType type) { AddChild(expression, Roles.Expression); AddChild(type, Roles.Type); }
public CastExpression(AstType castToType, Expression expression) { AddChild(castToType, Roles.Type); AddChild(expression, Roles.Expression); }
IEnumerable<string> GenerateNameProposals(AstType type) { if (type is PrimitiveType) { var pt = (PrimitiveType)type; switch (pt.Keyword) { case "object": yield return "o"; yield return "obj"; break; case "bool": yield return "b"; yield return "pred"; break; case "double": case "float": case "decimal": yield return "d"; yield return "f"; yield return "m"; break; default: yield return "i"; yield return "j"; yield return "k"; break; } yield break; } string name; if (type is SimpleType) { name = ((SimpleType)type).Identifier; } else if (type is MemberType) { name = ((MemberType)type).MemberName; } else { yield break; } var names = WordParser.BreakWords(name); var possibleName = new StringBuilder(); for (int i = 0; i < names.Count; i++) { possibleName.Length = 0; for (int j = i; j < names.Count; j++) { if (string.IsNullOrEmpty(names [j])) { continue; } if (j == i) { names [j] = Char.ToLower(names [j] [0]) + names [j].Substring(1); } possibleName.Append(names [j]); } yield return possibleName.ToString(); } }
public CastBlock(IEmitter emitter, AstType astType) : base(emitter, astType) { this.Emitter = emitter; this.AstType = astType; }
void QualifiedTypeName(out AstType type) { if (la.kind == 130) { Get(); } else if (StartOf(4)) { Identifier(); } else SynErr(246); type = new SimpleType(TextTokenType.Text, t.val, t.Location); while (la.kind == 26) { Get(); Identifier(); type = new QualifiedType(type, new Identifier (TextTokenType.Text, t.val, t.Location)); } }
bool TryConvertAssignmentExpressionIntoVariableDeclaration(Statement declarationPoint, AstType type, string variableName) { // convert the declarationPoint into a VariableDeclarationStatement ExpressionStatement es = declarationPoint as ExpressionStatement; if (es != null) { return TryConvertAssignmentExpressionIntoVariableDeclaration(es.Expression, type, variableName); } return false; }
void DeclareVariableInBlock(DefiniteAssignmentAnalysis daa, BlockStatement block, AstType type, string variableName, ILVariable v, bool allowPassIntoLoops) { // declarationPoint: The point where the variable would be declared, if we decide to declare it in this block Statement declarationPoint = null; // Check whether we can move down the variable into the sub-blocks bool canMoveVariableIntoSubBlocks = FindDeclarationPoint(daa, variableName, allowPassIntoLoops, block, out declarationPoint); if (declarationPoint == null) { // The variable isn't used at all return; } if (canMoveVariableIntoSubBlocks) { // Declare the variable within the sub-blocks foreach (Statement stmt in block.Statements) { ForStatement forStmt = stmt as ForStatement; if (forStmt != null && forStmt.Initializers.Count == 1) { // handle the special case of moving a variable into the for initializer if (TryConvertAssignmentExpressionIntoVariableDeclaration(forStmt.Initializers.Single(), type, variableName)) { continue; } } UsingStatement usingStmt = stmt as UsingStatement; if (usingStmt != null && usingStmt.ResourceAcquisition is AssignmentExpression) { // handle the special case of moving a variable into a using statement if (TryConvertAssignmentExpressionIntoVariableDeclaration((Expression)usingStmt.ResourceAcquisition, type, variableName)) { continue; } } foreach (AstNode child in stmt.Children) { BlockStatement subBlock = child as BlockStatement; if (subBlock != null) { DeclareVariableInBlock(daa, subBlock, type, variableName, v, allowPassIntoLoops); } else if (HasNestedBlocks(child)) { foreach (BlockStatement nestedSubBlock in child.Children.OfType <BlockStatement>()) { DeclareVariableInBlock(daa, nestedSubBlock, type, variableName, v, allowPassIntoLoops); } } } } } else { // Try converting an assignment expression into a VariableDeclarationStatement if (!TryConvertAssignmentExpressionIntoVariableDeclaration(declarationPoint, type, variableName)) { // Declare the variable in front of declarationPoint variablesToDeclare.Add(new VariableToDeclare { Type = type, Name = variableName, ILVariable = v, InsertionPoint = declarationPoint }); } } }
/// <summary> /// Adds type arguments to the result type. /// </summary> /// <param name="result">The result AST node (a SimpleType or MemberType)</param> /// <param name="typeDef">The type definition that owns the type parameters</param> /// <param name="typeArguments">The list of type arguments</param> /// <param name="startIndex">Index of first type argument to add</param> /// <param name="endIndex">Index after last type argument to add</param> void AddTypeArguments(AstType result, ITypeDefinition typeDef, IList<IType> typeArguments, int startIndex, int endIndex) { Debug.Assert(endIndex <= typeDef.TypeParameterCount); for (int i = startIndex; i < endIndex; i++) { if (ConvertUnboundTypeArguments && typeArguments[i].Kind == TypeKind.UnboundTypeArgument) { result.AddChild(new SimpleType(typeDef.TypeParameters[i].Name), Roles.TypeArgument); } else { result.AddChild(ConvertType(typeArguments[i]), Roles.TypeArgument); } } }
bool TryConvertAssignmentExpressionIntoVariableDeclaration(Expression expression, AstType type, string variableName) { AssignmentExpression ae = expression as AssignmentExpression; if (ae != null && ae.Operator == AssignmentOperatorType.Assign) { IdentifierExpression ident = ae.Left as IdentifierExpression; if (ident != null && ident.Identifier == variableName) { variablesToDeclare.Add(new VariableToDeclare { Type = type, Name = variableName, ILVariable = ident.Annotation <ILVariable>(), ReplacedAssignment = ae }); return(true); } } return(false); }
private void BuildTypedArguments(AstType type) { var simpleType = type as SimpleType; if (simpleType != null) { AstNodeCollection<AstType> typedArguments = simpleType.TypeArguments; IList<ITypeParameter> typeParams = null; if (this.ResolveResult.Member.DeclaringTypeDefinition != null) { typeParams = this.ResolveResult.Member.DeclaringTypeDefinition.TypeParameters; } else if (this.ResolveResult.Member is SpecializedMethod) { typeParams = ((SpecializedMethod)this.ResolveResult.Member).TypeParameters; } this.TypeArguments = new TypeParamExpression[typedArguments.Count]; var list = typedArguments.ToList(); for (int i = 0; i < list.Count; i++) { this.TypeArguments[i] = new TypeParamExpression(typeParams[i].Name, list[i], null); } } }
static List <AstNode> SearchCasts(RefactoringContext ctx, Statement embeddedStatement, Expression obj, AstType type, out ResolveResult rr) { var cast = new Choice { PatternHelper.OptionalParentheses(PatternHelper.OptionalParentheses(obj.Clone()).CastTo(type.Clone())), PatternHelper.OptionalParentheses(PatternHelper.OptionalParentheses(obj.Clone()).CastAs(type.Clone())) }; rr = ctx.Resolve(type); if (rr == null || rr.IsError) { return(null); } return(embeddedStatement.DescendantNodesAndSelf(n => !cast.IsMatch(n)).Where(n => cast.IsMatch(n)).ToList()); }
protected virtual void EmitCastExpression(Expression expression, AstType type, string method) { var itype = this.Emitter.BridgeTypes.ToType(type); var enumType = itype; if (NullableType.IsNullable(enumType)) { enumType = NullableType.GetUnderlyingType(enumType); } var castToEnum = enumType.Kind == TypeKind.Enum; if (castToEnum) { itype = enumType.GetDefinition().EnumUnderlyingType; var enumMode = this.Emitter.Validator.EnumEmitMode(enumType); if (enumMode >= 3 && enumMode < 7) { itype = this.Emitter.Resolver.Compilation.FindType(KnownTypeCode.String); } } if (expression is NullReferenceExpression || (method != CS.Ops.IS && Helpers.IsIgnoreCast(type, this.Emitter))) { if (expression is ParenthesizedExpression) { expression = ((ParenthesizedExpression)expression).Expression; } expression.AcceptVisitor(this.Emitter); return; } if (method == CS.Ops.CAST) { var cast_rr = this.Emitter.Resolver.ResolveNode(this.CastExpression, this.Emitter); if (cast_rr is ConstantResolveResult) { var expectedType = this.Emitter.Resolver.Resolver.GetExpectedType(this.CastExpression); var value = ((ConstantResolveResult)cast_rr).ConstantValue; this.WriteCastValue(value, expectedType); return; } else { var conv_rr = cast_rr as ConversionResolveResult; if (conv_rr != null && conv_rr.Input is ConstantResolveResult && !conv_rr.Conversion.IsUserDefined) { var expectedType = this.Emitter.Resolver.Resolver.GetExpectedType(this.CastExpression); var value = ((ConstantResolveResult)conv_rr.Input).ConstantValue; this.WriteCastValue(value, expectedType); return; } } } if (method == CS.Ops.IS && castToEnum) { this.Write("Bridge.is("); expression.AcceptVisitor(this.Emitter); this.Write(", "); this.Write(BridgeTypes.ToJsName(itype, this.Emitter)); this.Write(")"); return; } var expressionrr = this.Emitter.Resolver.ResolveNode(expression, this.Emitter); var typerr = this.Emitter.Resolver.ResolveNode(type, this.Emitter); if (expressionrr.Type.Equals(itype)) { if (method == CS.Ops.IS) { this.Write(JS.Funcs.BRIDGE_HASVALUE); this.WriteOpenParentheses(); } expression.AcceptVisitor(this.Emitter); if (method == CS.Ops.IS) { this.Write(")"); } return; } bool isCastAttr; string castCode = this.GetCastCode(expression, type, out isCastAttr); bool isResultNullable = NullableType.IsNullable(typerr.Type); if (castCode != null) { this.EmitInlineCast(expressionrr, expression, type, castCode, isCastAttr, method); return; } bool isCast = method == CS.Ops.CAST; if (isCast) { if (ConversionBlock.IsUserDefinedConversion(this, this.CastExpression.Expression) || ConversionBlock.IsUserDefinedConversion(this, this.CastExpression)) { expression.AcceptVisitor(this.Emitter); return; } } var conversion = this.Emitter.Resolver.Resolver.GetConversion(expression); if (conversion.IsNumericConversion || conversion.IsEnumerationConversion || (isCast && conversion.IsIdentityConversion)) { expression.AcceptVisitor(this.Emitter); return; } var simpleType = type as SimpleType; bool hasValue = false; if (simpleType != null && simpleType.Identifier == "dynamic") { if (method == CS.Ops.CAST || method == CS.Ops.AS) { expression.AcceptVisitor(this.Emitter); return; } else if (method == CS.Ops.IS) { hasValue = true; method = "hasValue"; } } bool unbox = !NullableType.IsNullable(itype) && isCast && conversion.IsUnboxingConversion; if (unbox) { this.Write("System.Nullable.getValue("); } this.Write(JS.NS.BRIDGE); this.WriteDot(); this.Write(method); this.WriteOpenParentheses(); expression.AcceptVisitor(this.Emitter); if (!hasValue) { this.WriteComma(); this.EmitCastType(itype); } if (isResultNullable && method != CS.Ops.IS) { this.WriteComma(); this.WriteScript(true); } this.WriteCloseParentheses(); if (unbox) { this.Write(")"); } }
void Fix(Script script, MethodDeclaration methodDeclaration, TypeDeclaration typeDeclaration) { var newTypeDeclaration = (TypeDeclaration)typeDeclaration.Clone(); var resolver = ctx.GetResolverStateAfter(typeDeclaration.LBraceToken); var typeResolve = resolver.ResolveSimpleName("IDisposable", new List <IType>()) as TypeResolveResult; bool canShortenIDisposable = typeResolve != null && typeResolve.Type.FullName == "System.IDisposable"; string interfaceName = (canShortenIDisposable ? string.Empty : "System.") + "IDisposable"; newTypeDeclaration.BaseTypes.Add(new SimpleType(interfaceName)); foreach (var method in DisposeMethods(newTypeDeclaration).ToList()) { if (typeDeclaration.ClassType == ClassType.Interface) { method.Remove(); } else { method.Modifiers &= ~Modifiers.Private; method.Modifiers &= ~Modifiers.Protected; method.Modifiers &= ~Modifiers.Internal; method.Modifiers |= Modifiers.Public; } } if (typeDeclaration.ClassType == ClassType.Interface) { var disposeMember = ((MemberResolveResult)ctx.Resolve(methodDeclaration)).Member; script.DoGlobalOperationOn(new List <IEntity>() { disposeMember }, (nCtx, nScript, nodes) => { List <Tuple <AstType, AstType> > pendingChanges = new List <Tuple <AstType, AstType> >(); foreach (var node in nodes) { var method = node as MethodDeclaration; if (method != null && !method.PrivateImplementationType.IsNull) { var nResolver = ctx.GetResolverStateAfter(typeDeclaration.LBraceToken); var nTypeResolve = nResolver.ResolveSimpleName("IDisposable", new List <IType>()) as TypeResolveResult; bool nCanShortenIDisposable = nTypeResolve != null && nTypeResolve.Type.FullName == "System.IDisposable"; string nInterfaceName = (nCanShortenIDisposable ? string.Empty : "System.") + "IDisposable"; pendingChanges.Add(Tuple.Create(method.PrivateImplementationType, AstType.Create(nInterfaceName))); } } foreach (var change in pendingChanges) { nScript.Replace(change.Item1, change.Item2); } }, "Fix explicitly implemented members"); } script.Replace(typeDeclaration, newTypeDeclaration); }
public UsingAliasDeclaration(string alias, AstType import) { AddChild(Identifier.Create (alias), AliasRole); AddChild(import, ImportRole); }
public TypeOfExpression(AstType type) { AddChild(type, Roles.Type); }
public DefaultValueExpression(AstType type) { AddChild(type, Roles.Type); }
void DeclareVariableInBlock(DefiniteAssignmentAnalysis daa, BlockStatement block, AstType type, string variableName, bool allowPassIntoLoops) { // declarationPoint: The point where the variable would be declared, if we decide to declare it in this block Statement declarationPoint = null; // Check whether we can move down the variable into the sub-blocks bool canMoveVariableIntoSubBlocks = FindDeclarationPoint(daa, variableName, allowPassIntoLoops, block, out declarationPoint); if (declarationPoint == null) { // The variable isn't used at all return; } if (canMoveVariableIntoSubBlocks) { // Declare the variable within the sub-blocks foreach (Statement stmt in block.Statements) { ForStatement forStmt = stmt as ForStatement; if (forStmt != null && forStmt.Initializers.Count == 1) { // handle the special case of moving a variable into the for initializer if (TryConvertAssignmentExpressionIntoVariableDeclaration(forStmt.Initializers.Single(), type, variableName)) continue; } UsingStatement usingStmt = stmt as UsingStatement; if (usingStmt != null && usingStmt.ResourceAcquisition is AssignmentExpression) { // handle the special case of moving a variable into a using statement if (TryConvertAssignmentExpressionIntoVariableDeclaration((Expression)usingStmt.ResourceAcquisition, type, variableName)) continue; } foreach (AstNode child in stmt.Children) { BlockStatement subBlock = child as BlockStatement; if (subBlock != null) { DeclareVariableInBlock(daa, subBlock, type, variableName, allowPassIntoLoops); } else if (HasNestedBlocks(child)) { foreach (BlockStatement nestedSubBlock in child.Children.OfType<BlockStatement>()) { DeclareVariableInBlock(daa, nestedSubBlock, type, variableName, allowPassIntoLoops); } } } } } else { // Try converting an assignment expression into a VariableDeclarationStatement if (!TryConvertAssignmentExpressionIntoVariableDeclaration(declarationPoint, type, variableName)) { // Declare the variable in front of declarationPoint variablesToDeclare.Add(new VariableToDeclare { Type = type, Name = variableName, InsertionPoint = declarationPoint }); } } }
public IType ToType(AstType type) { var resolveResult = this.Emitter.Resolver.ResolveNode(type, this.Emitter); return(resolveResult.Type); }
bool TryConvertAssignmentExpressionIntoVariableDeclaration(Expression expression, AstType type, string variableName) { AssignmentExpression ae = expression as AssignmentExpression; if (ae != null && ae.Operator == AssignmentOperatorType.Assign) { IdentifierExpression ident = ae.Left as IdentifierExpression; if (ident != null && ident.Identifier == variableName) { variablesToDeclare.Add(new VariableToDeclare { Type = type, Name = variableName, ReplacedAssignment = ae }); return true; } } return false; }
public ParameterDeclaration(AstType type, string name, ParameterModifier modifier = ParameterModifier.None) { Type = type; Name = name; ParameterModifier = modifier; }
/// <summary> /// Check if the type should be skipped to generate 'Contract.Ensures' and 'Contract.Requires' statemets. /// </summary> /// <param name="type">the type</param> /// <returns>true: skip type</returns> public static bool IsSkipType(AstType type) { string typeName = type.HasChildren ? type.FirstChild.ToString() : type.ToString(); if (SkipTypes == null) { return false; } return SkipTypes.Any(s => s.ToUpper() == typeName.ToUpper()); }
public TypeBlock(IEmitter emitter, AstType type) : base(emitter, type) { this.Emitter = emitter; this.Type = type; }
public TypeParamExpression(string name, AstType type, IType iType, bool inherited = false) { this.Name = name; this.AstType = type; this.IType = iType; this.Inherited = inherited; }
public virtual TypeDefinition GetTypeDefinition(AstType reference, bool safe = false) { var resolveResult = this.Resolver.ResolveNode(reference, this) as TypeResolveResult; var type = this.BridgeTypes.Get(resolveResult.Type, safe); return type != null ? type.TypeDefinition : null; }
private Expression GetDefaultFieldInitializer(AstType type) { return(new PrimitiveExpression(Inspector.GetDefaultFieldValue(type, this.Resolver), "?")); }
protected virtual void EmitCastExpression(Expression expression, AstType type, string method) { var itype = this.Emitter.BridgeTypes.ToType(type); bool isCastAttr; string castCode = this.GetCastCode(expression, type, out isCastAttr); var enumType = itype; if (NullableType.IsNullable(enumType)) { enumType = NullableType.GetUnderlyingType(enumType); } var castToEnum = enumType.Kind == TypeKind.Enum; if (castToEnum) { itype = enumType.GetDefinition().EnumUnderlyingType; var enumMode = Helpers.EnumEmitMode(enumType); if (enumMode >= 3 && enumMode < 7) { itype = this.Emitter.Resolver.Compilation.FindType(KnownTypeCode.String); } } if (expression is NullReferenceExpression || (method != CS.Ops.IS && Helpers.IsIgnoreCast(type, this.Emitter))) { if (expression is ParenthesizedExpression) { expression = ((ParenthesizedExpression)expression).Expression; } expression.AcceptVisitor(this.Emitter); return; } var expressionrr = this.Emitter.Resolver.ResolveNode(expression, this.Emitter); var typerr = this.Emitter.Resolver.ResolveNode(type, this.Emitter); if (expressionrr.Type.Kind == TypeKind.Enum) { var enumMode = Helpers.EnumEmitMode(expressionrr.Type); if (enumMode >= 3 && enumMode < 7 && Helpers.IsIntegerType(itype, this.Emitter.Resolver)) { throw new EmitterException(this.CastExpression, "Enum underlying type is string and cannot be casted to number"); } } if (method == CS.Ops.CAST && expressionrr.Type.Kind != TypeKind.Enum) { var cast_rr = this.Emitter.Resolver.ResolveNode(this.CastExpression, this.Emitter); if (cast_rr is ConstantResolveResult) { var expectedType = this.Emitter.Resolver.Resolver.GetExpectedType(this.CastExpression); var value = ((ConstantResolveResult)cast_rr).ConstantValue; this.WriteCastValue(value, expectedType); return; } else { var conv_rr = cast_rr as ConversionResolveResult; if (conv_rr != null && conv_rr.Input is ConstantResolveResult && !conv_rr.Conversion.IsUserDefined) { var expectedType = this.Emitter.Resolver.Resolver.GetExpectedType(this.CastExpression); var value = ((ConstantResolveResult)conv_rr.Input).ConstantValue; this.WriteCastValue(value, expectedType); return; } } } if (method == CS.Ops.IS && castToEnum) { this.Write(JS.Types.Bridge.IS); this.WriteOpenParentheses(); expression.AcceptVisitor(this.Emitter); this.Write(", "); this.Write(BridgeTypes.ToJsName(itype, this.Emitter)); this.Write(")"); return; } if (expressionrr.Type.Equals(itype)) { if (method == CS.Ops.IS) { this.Write(JS.Funcs.BRIDGE_HASVALUE); this.WriteOpenParentheses(); } expression.AcceptVisitor(this.Emitter); if (method == CS.Ops.IS) { this.Write(")"); } return; } bool isResultNullable = NullableType.IsNullable(typerr.Type); if (castCode != null) { this.EmitInlineCast(expressionrr, expression, type, castCode, isCastAttr, method); return; } bool isCast = method == CS.Ops.CAST; if (isCast) { if (ConversionBlock.IsUserDefinedConversion(this, this.CastExpression.Expression) || ConversionBlock.IsUserDefinedConversion(this, this.CastExpression)) { expression.AcceptVisitor(this.Emitter); return; } } var conversion = this.Emitter.Resolver.Resolver.GetConversion(expression); if (conversion.IsNumericConversion || conversion.IsEnumerationConversion || (isCast && conversion.IsIdentityConversion)) { expression.AcceptVisitor(this.Emitter); return; } var simpleType = type as SimpleType; bool hasValue = false; if (simpleType != null && simpleType.Identifier == "dynamic") { if (method == CS.Ops.CAST || method == CS.Ops.AS) { expression.AcceptVisitor(this.Emitter); return; } else if (method == CS.Ops.IS) { hasValue = true; method = "hasValue"; } } bool unbox = this.Emitter.Rules.Boxing == BoxingRule.Managed && !(itype.IsReferenceType.HasValue ? itype.IsReferenceType.Value : true) && !NullableType.IsNullable(itype) && isCast && conversion.IsUnboxingConversion; if (unbox) { this.Write("System.Nullable.getValue("); } var typeDef = itype.Kind == TypeKind.TypeParameter ? null : this.Emitter.GetTypeDefinition(type, true); if (typeDef != null && method == CS.Ops.IS && itype.Kind != TypeKind.Interface && this.Emitter.Validator.IsObjectLiteral(typeDef) && this.Emitter.Validator.GetObjectCreateMode(typeDef) == 0) { throw new EmitterException(type, $"ObjectLiteral type ({itype.FullName}) with Plain mode cannot be used in 'is' operator. Please define cast logic in Cast attribute or use Constructor mode."); } this.Write(JS.NS.BRIDGE); this.WriteDot(); this.Write(method); this.WriteOpenParentheses(); expression.AcceptVisitor(this.Emitter); if (!hasValue) { this.WriteComma(); this.EmitCastType(itype); } if (isResultNullable && method != CS.Ops.IS) { this.WriteComma(); this.WriteScript(true); } this.WriteCloseParentheses(); if (unbox) { this.Write(")"); } }
bool ContainsAnonymousType(AstType type) { foreach (AstType t in type.DescendantsAndSelf.OfType<AstType>()) { TypeReference tr = t.Annotation<TypeReference>(); if (tr != null && tr.IsAnonymousType()) return true; } return false; }
public VariableDeclarationStatement(object annotations, AstType type, string name, Expression initializer = null) { this.Type = type; this.Variables.Add(new VariableInitializer(annotations, name, initializer)); }
void AddTypeArguments(ATypeNameExpression texpr, AstType result) { var unbound = texpr.TypeArguments as UnboundTypeArguments; if (unbound != null) { var loc2 = LocationsBag.GetLocations(texpr.TypeArguments); if (loc2 == null) return; int j = 0; if (j < loc2.Count) result.AddChild(new CSharpTokenNode(Convert(loc2 [j++]), Roles.LChevron), Roles.LChevron); while (j < loc2.Count - 1) { result.AddChild (new SimpleType (), Roles.TypeArgument); result.AddChild(new CSharpTokenNode(Convert(loc2 [j++]), Roles.LChevron), Roles.Comma); } if (j < loc2.Count) { result.AddChild (new SimpleType (), Roles.TypeArgument); result.AddChild(new CSharpTokenNode(Convert(loc2 [j++]), Roles.RChevron), Roles.RChevron); } return; } if (texpr.TypeArguments == null || texpr.TypeArguments.Args == null) return; var loc = LocationsBag.GetLocations(texpr.TypeArguments); if (loc != null && loc.Count >= 2) result.AddChild(new CSharpTokenNode(Convert(loc [loc.Count - 2]), Roles.LChevron), Roles.LChevron); int i = 0; foreach (var arg in texpr.TypeArguments.Args) { result.AddChild(ConvertToType(arg), Roles.TypeArgument); if (loc != null && i < loc.Count - 2) result.AddChild(new CSharpTokenNode(Convert(loc [i++]), Roles.Comma), Roles.Comma); } if (loc != null && loc.Count >= 2) result.AddChild(new CSharpTokenNode(Convert(loc [loc.Count - 1]), Roles.RChevron), Roles.RChevron); }
public IType ResolveType(AstType type) { return(resolver.Resolve(type, cancellationToken).Type); }
void WritePrivateImplementationType(AstType privateImplementationType) { if (!privateImplementationType.IsNull) { privateImplementationType.AcceptVisitor(this); WriteToken(Roles.Dot); } }
static CodeAction CreateAction(RefactoringContext context, string methodName, AstType returnType, IEnumerable <ParameterDeclaration> parameters, bool createInOtherType, bool isStatic, ResolveResult targetResolveResult) { return(new CodeAction(context.TranslateString("Create method"), script => { var decl = new MethodDeclaration() { ReturnType = returnType, Name = methodName, Body = new BlockStatement() { new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException"))) } }; decl.Parameters.AddRange(parameters); if (isStatic) { decl.Modifiers |= Modifiers.Static; } if (createInOtherType) { if (targetResolveResult.Type.Kind == TypeKind.Interface) { decl.Body = null; decl.Modifiers = Modifiers.None; } else { decl.Modifiers |= Modifiers.Public; } script.InsertWithCursor(context.TranslateString("Create method"), decl, targetResolveResult.Type.GetDefinition()); return; } script.InsertWithCursor(context.TranslateString("Create method"), decl, Script.InsertPosition.Before); })); }
void PrimitiveTypeName(out AstType type) { type = null; switch (la.kind) { case 168: { Get(); type = new PrimitiveType("Object", t.Location); break; } case 68: { Get(); type = new PrimitiveType("Boolean", t.Location); break; } case 99: { Get(); type = new PrimitiveType("Date", t.Location); break; } case 82: { Get(); type = new PrimitiveType("Char", t.Location); break; } case 208: { Get(); type = new PrimitiveType("String", t.Location); break; } case 100: { Get(); type = new PrimitiveType("Decimal", t.Location); break; } case 71: { Get(); type = new PrimitiveType("Byte", t.Location); break; } case 201: { Get(); type = new PrimitiveType("Short", t.Location); break; } case 141: { Get(); type = new PrimitiveType("Integer", t.Location); break; } case 151: { Get(); type = new PrimitiveType("Long", t.Location); break; } case 202: { Get(); type = new PrimitiveType("Single", t.Location); break; } case 109: { Get(); type = new PrimitiveType("Double", t.Location); break; } case 221: { Get(); type = new PrimitiveType("UInteger", t.Location); break; } case 222: { Get(); type = new PrimitiveType("ULong", t.Location); break; } case 225: { Get(); type = new PrimitiveType("UShort", t.Location); break; } case 196: { Get(); type = new PrimitiveType("SByte", t.Location); break; } default: SynErr(245); break; } }
protected virtual bool WriteObject(string objectName, List <TypeConfigItem> members, string format, string interfaceFormat) { bool hasProperties = this.HasProperties(objectName, members); int pos = 0; IWriterInfo writer = null; bool beginBlock = false; if (hasProperties && objectName != null && !this.IsObjectLiteral) { beginBlock = true; pos = this.Emitter.Output.Length; writer = this.SaveWriter(); this.EnsureComma(); this.Write(objectName); this.WriteColon(); this.BeginBlock(); } bool isProperty = JS.Fields.PROPERTIES == objectName; bool isField = JS.Fields.FIELDS == objectName; int count = 0; foreach (var member in members) { object constValue = null; bool isPrimitive = false; var primitiveExpr = member.Initializer as PrimitiveExpression; bool write = false; bool writeScript = false; if (primitiveExpr != null) { //isPrimitive = true; constValue = primitiveExpr.Value; ResolveResult rr = null; if (member.VarInitializer != null) { rr = this.Emitter.Resolver.ResolveNode(member.VarInitializer, this.Emitter); } else { rr = this.Emitter.Resolver.ResolveNode(member.Entity, this.Emitter); } if (rr != null && rr.Type.Kind == TypeKind.Enum) { constValue = Helpers.GetEnumValue(this.Emitter, rr.Type, constValue); writeScript = true; } } if (constValue is RawValue) { constValue = constValue.ToString(); write = true; writeScript = false; } var isNull = member.Initializer.IsNull || member.Initializer is NullReferenceExpression || member.Initializer.Parent == null; if (!isNull && !isPrimitive) { var constrr = this.Emitter.Resolver.ResolveNode(member.Initializer, this.Emitter); if (constrr != null && constrr.IsCompileTimeConstant) { //isPrimitive = true; constValue = constrr.ConstantValue; var expectedType = this.Emitter.Resolver.Resolver.GetExpectedType(member.Initializer); if (!expectedType.Equals(constrr.Type) && expectedType.Kind != TypeKind.Dynamic) { try { constValue = Convert.ChangeType(constValue, ReflectionHelper.GetTypeCode(expectedType)); } catch (Exception) { this.Emitter.Log.Warn($"FieldBlock: Convert.ChangeType is failed. Value type: {constrr.Type.FullName}, Target type: {expectedType.FullName}"); } } if (constrr.Type.Kind == TypeKind.Enum) { constValue = Helpers.GetEnumValue(this.Emitter, constrr.Type, constrr.ConstantValue); } writeScript = true; } } var isNullable = false; if (isPrimitive && constValue is AstType) { var itype = this.Emitter.Resolver.ResolveNode((AstType)constValue, this.Emitter); if (NullableType.IsNullable(itype.Type)) { isNullable = true; } } string tpl = null; IMember templateMember = null; MemberResolveResult init_rr = null; if (isField && member.VarInitializer != null) { init_rr = this.Emitter.Resolver.ResolveNode(member.VarInitializer, this.Emitter) as MemberResolveResult; tpl = init_rr != null?this.Emitter.GetInline(init_rr.Member) : null; if (tpl != null) { templateMember = init_rr.Member; } } bool isAutoProperty = false; if (isProperty) { var member_rr = this.Emitter.Resolver.ResolveNode(member.Entity, this.Emitter) as MemberResolveResult; var property = (IProperty)member_rr.Member; isAutoProperty = Helpers.IsAutoProperty(property); } bool written = false; if (!isNull && (!isPrimitive || constValue is AstType || tpl != null) && !(isProperty && !IsObjectLiteral && !isAutoProperty)) { string value = null; bool needContinue = false; string defValue = ""; if (!isPrimitive) { var oldWriter = this.SaveWriter(); this.NewWriter(); member.Initializer.AcceptVisitor(this.Emitter); value = this.Emitter.Output.ToString(); this.RestoreWriter(oldWriter); ResolveResult rr = null; AstType astType = null; if (member.VarInitializer != null) { rr = this.Emitter.Resolver.ResolveNode(member.VarInitializer, this.Emitter); } else { astType = member.Entity.ReturnType; rr = this.Emitter.Resolver.ResolveNode(member.Entity, this.Emitter); } constValue = Inspector.GetDefaultFieldValue(rr.Type, astType); if (rr.Type.Kind == TypeKind.Enum) { constValue = Helpers.GetEnumValue(this.Emitter, rr.Type, constValue); } isNullable = NullableType.IsNullable(rr.Type); needContinue = constValue is IType; writeScript = true; /*if (needContinue && !(member.Initializer is ObjectCreateExpression)) * { * defValue = " || " + Inspector.GetStructDefaultValue((IType)constValue, this.Emitter); * }*/ } else if (constValue is AstType) { value = isNullable ? "null" : Inspector.GetStructDefaultValue((AstType)constValue, this.Emitter); constValue = value; write = true; needContinue = !isProperty && !isNullable; } var name = member.GetName(this.Emitter); bool isValidIdentifier = Helpers.IsValidIdentifier(name); if (isProperty && isPrimitive) { constValue = "null"; if (this.IsObjectLiteral) { written = true; if (isValidIdentifier) { this.Write(string.Format("this.{0} = {1};", name, value)); } else { this.Write(string.Format("this[{0}] = {1};", AbstractEmitterBlock.ToJavaScript(name, this.Emitter), value)); } this.WriteNewLine(); } else { this.Injectors.Add(string.Format(name.StartsWith("\"") || !isValidIdentifier ? "this[{0}] = {1};" : "this.{0} = {1};", isValidIdentifier ? name : AbstractEmitterBlock.ToJavaScript(name, this.Emitter), value)); } } else { if (this.IsObjectLiteral) { written = true; if (isValidIdentifier) { this.Write(string.Format("this.{0} = {1};", name, value + defValue)); } else { this.Write(string.Format("this[{0}] = {1};", AbstractEmitterBlock.ToJavaScript(name, this.Emitter), value + defValue)); } this.WriteNewLine(); } else if (tpl != null) { if (!tpl.Contains("{0}")) { tpl = tpl + " = {0};"; } string v = null; if (!isNull && (!isPrimitive || constValue is AstType)) { v = value + defValue; } else { if (write) { v = constValue != null?constValue.ToString() : ""; } else if (writeScript) { v = AbstractEmitterBlock.ToJavaScript(constValue, this.Emitter); } else { var oldWriter = this.SaveWriter(); this.NewWriter(); member.Initializer.AcceptVisitor(this.Emitter); v = this.Emitter.Output.ToString(); this.RestoreWriter(oldWriter); } } tpl = Helpers.ConvertTokens(this.Emitter, tpl, templateMember); tpl = tpl.Replace("{this}", "this").Replace("{0}", v); if (!tpl.EndsWith(";")) { tpl += ";"; } this.Injectors.Add(tpl); } else { var rr = this.Emitter.Resolver.ResolveNode(member.Initializer, this.Emitter) as CSharpInvocationResolveResult; bool isDefaultInstance = rr != null && rr.Member.SymbolKind == SymbolKind.Constructor && rr.Arguments.Count == 0 && rr.InitializerStatements.Count == 0 && rr.Type.Kind == TypeKind.Struct; if (!isDefaultInstance) { if (isField && !isValidIdentifier) { this.Injectors.Add(string.Format("this[{0}] = {1};", name.StartsWith("\"") ? name : AbstractEmitterBlock.ToJavaScript(name, this.Emitter), value + defValue)); } else { this.Injectors.Add(string.Format(name.StartsWith("\"") ? interfaceFormat : format, name, value + defValue)); } } } } } count++; if (written) { continue; } bool withoutTypeParams = true; MemberResolveResult m_rr = null; if (member.Entity != null) { m_rr = this.Emitter.Resolver.ResolveNode(member.Entity, this.Emitter) as MemberResolveResult; if (m_rr != null) { withoutTypeParams = OverloadsCollection.ExcludeTypeParameterForDefinition(m_rr); } } var mname = member.GetName(this.Emitter, withoutTypeParams); if (this.TypeInfo.IsEnum && m_rr != null) { mname = this.Emitter.GetEntityName(m_rr.Member); } bool isValid = Helpers.IsValidIdentifier(mname); if (!isValid) { if (this.IsObjectLiteral) { mname = "[" + AbstractEmitterBlock.ToJavaScript(mname, this.Emitter) + "]"; } else { mname = AbstractEmitterBlock.ToJavaScript(mname, this.Emitter); } } if (this.IsObjectLiteral) { this.WriteThis(); if (isValid) { this.WriteDot(); } this.Write(mname); this.Write(" = "); } else { this.EnsureComma(); XmlToJsDoc.EmitComment(this, member.Entity, null, member.Entity is FieldDeclaration ? member.VarInitializer : null); this.Write(mname); this.WriteColon(); } bool close = false; if (isProperty && !IsObjectLiteral && !isAutoProperty) { var oldTempVars = this.Emitter.TempVariables; this.BeginBlock(); new VisitorPropertyBlock(this.Emitter, (PropertyDeclaration)member.Entity).Emit(); this.WriteNewLine(); this.EndBlock(); this.Emitter.Comma = true; this.Emitter.TempVariables = oldTempVars; continue; } if (constValue is AstType || constValue is IType) { this.Write("null"); if (!isNullable) { var name = member.GetName(this.Emitter); bool isValidIdentifier = Helpers.IsValidIdentifier(name); var value = constValue is AstType?Inspector.GetStructDefaultValue((AstType)constValue, this.Emitter) : Inspector.GetStructDefaultValue((IType)constValue, this.Emitter); if (!isValidIdentifier) { this.Injectors.Insert(BeginCounter++, string.Format("this[{0}] = {1};", name.StartsWith("\"") ? name : AbstractEmitterBlock.ToJavaScript(name, this.Emitter), value)); } else { this.Injectors.Insert(BeginCounter++, string.Format(name.StartsWith("\"") ? interfaceFormat : format, name, value)); } } } else if (write) { this.Write(constValue); } else if (writeScript) { this.WriteScript(constValue); } else { member.Initializer.AcceptVisitor(this.Emitter); } if (close) { this.Write(" }"); } if (this.IsObjectLiteral) { this.WriteSemiColon(true); } this.Emitter.Comma = true; } if (count > 0 && objectName != null && !IsObjectLiteral) { this.WriteNewLine(); this.EndBlock(); } else if (beginBlock) { this.Emitter.IsNewLine = writer.IsNewLine; this.Emitter.ResetLevel(writer.Level); this.Emitter.Comma = writer.Comma; this.Emitter.Output.Length = pos; } return(count > 0); }
void TypeName(out AstType type) { type = null; if (StartOf(2)) { PrimitiveTypeName(out type); } else if (StartOf(3)) { QualifiedTypeName(out type); } else SynErr(244); }
void CheckConversion(IType variableType, Expression expression) { if (variableType.Kind == TypeKind.Unknown) { return; // ignore error if the variable type is unknown } if (ctx.GetConversion(expression).IsValid) { return; // don't complain if the code is valid } var rr = ctx.Resolve(expression); if (rr.Type.Kind == TypeKind.Unknown) { return; // ignore error if expression type is unknown } var foundConversion = conversion.ExplicitConversion(rr, variableType); var builder = ctx.CreateTypeSystemAstBuilder(expression); AstType variableTypeNode = builder.ConvertType(variableType); AstType expressionTypeNode = builder.ConvertType(rr.Type); string title; List <CodeAction> fixes = new List <CodeAction>(); if (foundConversion.IsValid) { // CS0266: An explicit conversion exists -> suggested fix is to insert the cast title = string.Format(ctx.TranslateString("Cannot implicitly convert type `{0}' to `{1}'. An explicit conversion exists (are you missing a cast?)"), expressionTypeNode, variableTypeNode); string fixTitle = string.Format(ctx.TranslateString("Cast to '{0}'"), variableTypeNode); Action <Script> fixAction = script => { var right = expression.Clone(); var castRight = right.CastTo(variableTypeNode); script.Replace(expression, castRight); }; fixes.Add(new CodeAction(fixTitle, fixAction, expression)); } else { // CS0029: No explicit conversion -> Issue without suggested fix title = string.Format(ctx.TranslateString("Cannot implicitly convert type `{0}' to `{1}'"), expressionTypeNode, variableTypeNode); } if (expression.Parent is VariableInitializer) { var fd = expression.Parent.Parent as FieldDeclaration; if (fd != null) { fixes.Add(new CodeAction( ctx.TranslateString("Change field type"), script => { script.Replace(fd.ReturnType, ctx.CreateTypeSystemAstBuilder(fd).ConvertType(rr.Type)); }, expression )); } var lc = expression.Parent.Parent as VariableDeclarationStatement; if (lc != null) { fixes.Add(new CodeAction( ctx.TranslateString("Change local variable type"), script => { script.Replace(lc.Type, new SimpleType("var")); }, expression )); } } if (expression.Parent is ReturnStatement) { AstNode entityNode; var type = CS0126ReturnMustBeFollowedByAnyExpression.GetRequestedReturnType(ctx, expression.Parent, out entityNode); if (type != null) { var entity = entityNode as EntityDeclaration; if (entity != null) { fixes.Add(new CodeAction( ctx.TranslateString("Change return type"), script => { script.Replace(entity.ReturnType, ctx.CreateTypeSystemAstBuilder(entity).ConvertType(rr.Type)); }, expression )); } } } AddIssue(new CodeIssue(expression, title, fixes)); }