public JNode VisitNamedExpression(NamedExpression node) { var name = new JJsonMember { Name = node.Name }; if (name.Name.IsNullOrEmpty()) { throw new NotImplementedException(); //if (d.expression.e == cs_node.n_simple_name) // name.Name = ((CsSimpleName)d.expression).identifier.identifier; //else if (d.expression.e == cs_node.n_primary_expression_member_access) // name.Name = ((CsPrimaryExpressionMemberAccess)d.expression).identifier.identifier; } var value = VisitExpression(node.Expression); var ce = node.GetParentType(); var nativeJson = JMeta.UseNativeJsons(ce.GetDefinitionOrArrayType(Compiler)); if (!nativeJson) { name.Name = "get_" + name.Name; value = new JFunction { Block = new JBlock { Statements = new List <JStatement> { new JReturnStatement { Expression = value } } } }; } return(new JJsonNameValue { Name = name, Value = value }); }
protected bool ShouldExportProperty(IProperty pe) { if (pe.IsIndexer) { return(!pe.IsExplicitInterfaceImplementation); } if (pe.IsExplicitInterfaceImplementation) { return(false); } var att = pe.GetMetadata <JPropertyAttribute>(); if (att != null && !att.Export) { return(false); } if (JMeta.IsNativeField(pe)) { return(false); } //{ // if (Sk.InlineFields(pe.GetDeclaringTypeDefinition())) // return true; // return false; //} return(true); }
protected IEnumerable <IMember> GetExportedDeclaredAndGeneratedFields(ITypeDefinition ce, bool isStatic) { foreach (var pe in ce.GetFields(t => t.IsStatic == isStatic, GetMemberOptions.IgnoreInheritedMembers)) { if (!JMeta.IsJsExported(pe)) { continue; } yield return(pe); } foreach (var pe in ce.GetEvents(t => t.IsStatic == isStatic, GetMemberOptions.IgnoreInheritedMembers)) { if (!JMeta.IsJsExported(pe)) { continue; } yield return(pe); } foreach (var fe in GeneratePropertyFields(ce, isStatic)) { yield return(fe); } }
public static JMemberExpression EntityMethodToJsFunctionRef(IMethod me) { var ownerType = me.GetDeclaringTypeDefinition(); if (JMeta.IsGlobalMethod(me)) { var member = J.Member(JNaming.JName(me)); return(member); } else { var member = JNaming.JAccess(ownerType); if (!me.IsStatic) { if (JMeta.IsNativeType(ownerType)) { member = member.Member("prototype"); } else { member = member.Member("commonPrototype"); } } member = member.Member(JNaming.JName(me)); return(member); } }
//InvocationExpression GetConstructorBaseOrThisInvocation(IMethod ctor) //{ // var ctorNode = (ConstructorDeclaration)ctor.GetDeclaration(); // InvocationExpression node = null; // if (ctorNode != null && ctorNode.Initializer != null && !ctorNode.Initializer.IsNull) // { // var xxx = (CSharpInvocationResolveResult)ctorNode.Initializer.Resolve(); // //throw new NotImplementedException(); // //danel // var baseCtor = xxx.Member; // var id = new IdentifierExpression(baseCtor.Name); // id.SetResolveResult(new MemberResolveResult(null, baseCtor)); // node = new InvocationExpression(id); // node.SetResolveResult(xxx); // //{ entity = ctorNode.invoked_method, Target = ctorNode.invoked_method.Access() }; // //node.SetResolveResult( // // node.Arguments.AddRange(ctorNode.Initializer.Arguments); // } // else // { // var ce = ctor.GetDeclaringTypeDefinition(); // if (Sk.OmitInheritance(ce)) // return null; // var baseType = GetBaseClassIfValid(ce, true); // if (baseType != null) // { // var baseCtor = baseType.GetConstructor(); // if (baseCtor != null) // { // //danel // //throw new NotImplementedException(); // var id = new IdentifierExpression(baseCtor.Name); // id.SetResolveResult(new MemberResolveResult(null, baseCtor)); // node = new InvocationExpression(id);// { entity = baseCtor, expression = baseCtor.Access() }; // node.SetResolveResult(new CSharpInvocationResolveResult(null, baseCtor, null)); // } // } // } // return node; //} InvocationResolveResult GetConstructorBaseOrThisInvocation2(IMethod ctor) { var ctorNode = (ConstructorDeclaration)ctor.GetDeclaration(); InvocationResolveResult node = null; if (ctorNode != null && ctorNode.Initializer != null && !ctorNode.Initializer.IsNull) { var xxx = (CSharpInvocationResolveResult)ctorNode.Initializer.Resolve(); return(xxx); } else { var ce = ctor.GetDeclaringTypeDefinition(); if (JMeta.OmitInheritance(ce)) { return(null); } var baseType = GetBaseClassIfValid(ce, true); if (baseType != null) { var baseCtor = baseType.GetConstructors(t => t.Parameters.Count == 0, GetMemberOptions.IgnoreInheritedMembers).Where(t => !t.IsStatic).FirstOrDefault(); if (baseCtor != null) { return(baseCtor.AccessSelf().Invoke()); } } } return(node); }
public JNode VisitMemberResolveResult(MemberResolveResult res) { var me = res.Member; JNode node2; bool enumValuesAsNames; if (me == null) //TODO: dynamics { throw new NotImplementedException(); //var node3 = Js.Member(node.MemberName); //if (node.Target != null) // node3.PreviousMember = VisitExpression(node.Target); //return node3; } else if (IsEntityFunctionProperty(res.Member, res))//(Entity)node.entity)) { var pe = (IProperty)me; var xxx = new CSharpInvocationResolveResult(res.TargetResult, pe.Getter, null); node2 = Visit(xxx); return(node2); } else if (me.IsEnumMember() && JMeta.UseJsonEnums(me, out enumValuesAsNames)) { var me2 = (IField)me; if (enumValuesAsNames) { return(J.String(JNaming.JName(me2))); } else { return(J.Value(me2.ConstantValue)); } } //TODO: Support a way to override this (JsField.ConstantInlining=false) else if (res.IsCompileTimeConstant && !me.IsEnumMember()) { return(J.Value(res.ConstantValue)); } else { var node3 = JNaming.JAccess(me); node2 = node3; if (res.TargetResult != null && !me.IsStatic()) { var instanceContext = VisitExpression(res.TargetResult); if (node3.Name.IsNullOrEmpty()) //support Name="" { node2 = instanceContext; } else { node3.PreviousMember = instanceContext; } } } return(node2); }
private string GetJFilename(ITypeDefinition ce) { var outputDir = "out"; var att = JMeta.GetJsExportAttribute(Project.Compilation.MainAssembly); if (att != null && att.OutputDir != null) { outputDir = att.OutputDir; } return(Path.Combine(outputDir, JNaming.JName2(ce).RemoveGenericArgs().ToJs().Replace(".", "\\") + ".java")); }
bool IsNonStatic(IEntity me) { if (!me.IsStatic()) { return(true); } if (me is IMethod && JMeta.ExtensionImplementedInInstance((IMethod)me)) { return(true); } return(false); }
void ConvertCsToJs() { TriggerEvent(BeforeConvertCsToJs); JsModelImporter = new JModelImporter { Compiler = this, Project = Project, Log = Log, ExternalMetadata = CsExternalMetadata, AssemblyName = Args.AssemblyName, BeforeExportTypes = byFile => { var list = new List <ITypeDefinition>(); foreach (var list2 in byFile.Values) { list.AddRange(list2); } var skFiles = Project.GetNFiles(list); Project.ApplyNavigator(skFiles); } }; JsModelImporter.ConfigureJsTypeImporter += new Action <JTypeImporter>(JsModelImporter_ConfigureJsTypeImporter); var att = JMeta.GetJsExportAttribute(Project.Compilation.MainAssembly); if (att != null) { JsModelImporter.ExportComments = att.ExportComments; } JsModelImporter.Process(); SkJsFiles = new List <JFileWrapper>(); foreach (var group in JsModelImporter.ExportedTypes.GroupBy(t => GetJFilename(t.Type))) { var file = new JFileWrapper { JsFile = new JFile { Filename = group.Key }, Compiler = this, }; foreach (var et in group) { var unit = new JCompilationUnit { PackageName = et.Type.GetPackageName(), Declarations = { et.ClassDeclaration } }; file.JsFile.Units.Add(unit); SkJsFiles.Add(file); } } TriggerEvent(AfterConvertCsToJs); }
/// <summary> /// Returns base type of a type, only if base type is Clr or Prototype /// </summary> /// <param name="ce"></param> /// <returns></returns> protected virtual IType GetBaseClassIfValid(ITypeDefinition ce, bool recursive) { var baseClass = ce.GetBaseType(); while (baseClass != null) { if (JMeta.IsClrType(baseClass.GetDefinition()) || (JMeta.IsNativeType(baseClass.GetDefinition()) && !JMeta.IsGlobalType(baseClass.GetDefinition())) || !recursive) { return(baseClass); } baseClass = baseClass.GetBaseType(); } return(null); }
protected List <string> ExportMethodParameters(IMethod me) { var list = new List <string>(); if (!JMeta.IgnoreGenericMethodArguments(me) && me.GetGenericArguments().Count() > 0) { list.AddRange(me.GetGenericArguments().Select(t => t.Name)); } //if (me.Parameters.Where(t => t.IsOut || t.IsRef).FirstOrDefault() != null) //{ // throw new CompilerException(me, "Out and ref parameters are not supported"); //} list.AddRange(me.Parameters.Select(t => t.Name)); return(list); }
JsMode GetJsMode(ITypeDefinition ce) { var isGlobal = JMeta.IsGlobalType(ce); if (isGlobal) { return(JsMode.Global); } var isNative = JMeta.IsNativeType(ce); if (isNative) { return(JsMode.Prototype); } return(JsMode.Clr); }
static JMemberExpression JName2(IProperty pe) { var name = pe.Name; var att = pe.GetMetadata <JPropertyAttribute>(); if (att != null && att.Name != null) { name = att.Name; } else if (JMeta.IsNativeField(pe)) { name = name.ToJavaNaming(); } return(J.Member(JCodeImporter.JsIdentifier(name))); }
public virtual List <JEntityDeclaration> ExportMethod(IMethod me) { var jma = JMeta.GetJMethodAttribute(me); if (jma != null && (jma.Global || jma.GlobalCode)) { throw new NotSupportedException(); //return CreateGlobalImporter().ExportMethod(me); } else { var ce = me.GetDeclaringTypeDefinition(); var member = me.JAccess(); var func = new JFunction(); //func.Name = me.Name; func.Parameters = ExportMethodParameters(me); func.Block = ExportMethodBody(me); if (JsCodeImporter.SupportClrYield) { func = ApplyYield(func); } var typeParams = me.TypeParameters.Select(t => t.JAccess()).ToList(); var decl = new JMethodDeclaration { Name = JNaming.JName(me), MethodDefinition = me, MethodBody = func.Block, Parameters = ExportParameters(me.Parameters), Type = me.ReturnType.JAccess(), TypeParameters = typeParams, }; ImportModifiers(me, decl); if (me.IsOverride || me.ImplementedInterfaceMembers.IsNotNullOrEmpty()) { decl.Annotations.Add(new JAnnotationDeclaration { Name = "Override" }); } return(new List <JEntityDeclaration> { decl }); } }
public static JMemberExpression JAccess(this IEntity me) { if (me == null) { return(null); } if (me is ITypeDefinition) { return(JAccess((ITypeDefinition)me)); } if (me is IType) { return(JAccess((IType)me)); } var name = JName2(me); if (me.IsStatic()) { var member = name; if (JMeta.IsGlobalMember(me)) { return(member); } if (me is IMethod && JMeta.ExtensionImplementedInInstance((IMethod)me)) { return(member); } member.PreviousMember = JAccessStatic(me.DeclaringType); return(member); } else if (me.SymbolKind == SymbolKind.Constructor) { var att = JMeta.GetJMethodAttribute((IMethod)me); if (att != null && att.Name != null) //TODO: hack { return(J.Member(att.Name)); } var ce = me.DeclaringType; var member = (JMemberExpression)JAccess(ce); return(member); } return(name); }
static JMemberExpression JName2(IMethod me2) { IMethod me = me2; if (me.IsConstructor) { return(J.Member("")); } var att = me.GetMetadata <JMethodAttribute>(true); if (att != null && att.Name != null) { var name = att.Name; return(J.Member(name)); } var owner = me.GetOwner(); if (owner != null && owner is IProperty) { var pe = (IProperty)owner; if (pe.SymbolKind == SymbolKind.Indexer && JMeta.UseNativeIndexer(pe)) { return(null); } var name2 = JName2(pe); if (me.IsGetter()) { if (pe.Name.StartsWith("Is")) { name2.Name = name2.Name.ToJavaNaming(); } else { name2.Name = "get" + name2.Name; } } else { name2.Name = "set" + name2.Name; } return(name2); } return(J.Member(me.Name.ToJavaNaming())); }
private void SortByNativeInheritance(List <ITypeDefinition> list) { var list2 = list.Where(t => JMeta.IsNativeType(t) && t.GetBaseTypeDefinition() != null && JMeta.IsNativeType(t.GetBaseTypeDefinition())).ToList(); foreach (var ce in list2) { var ce3 = ce; while (true) { var baseCe = ce3.GetBaseTypeDefinition(); if (baseCe == null) { break; } MoveBefore(list, ce3, baseCe); ce3 = baseCe; } } }
/// <summary> /// Indicates that object is IProperty that uses getter setter functions, and not native fields /// </summary> /// <param name="entity"></param> /// <returns></returns> bool IsEntityFunctionProperty(IEntity entity, ResolveResult scope) { var pe = entity as IProperty; if (pe != null) { var ce = pe.DeclaringType; if (ce != null && ce.Kind == TypeKind.Anonymous) { var ce2 = scope.GetParentType(); if (ce2 != null && JMeta.UseNativeJsons(ce2)) { return(false); } } return(!JMeta.IsNativeField(pe) && !JMeta.UseNativeIndexer(pe)); // && !Sk.IsNativeProperty(pe); } return(false); }
/// <summary> /// Generates backing fields for automatic properties, and fake fields for properties who are defined as fields /// </summary> /// <param name="ce"></param> /// <returns></returns> protected IEnumerable <IField> GeneratePropertyFields(ITypeDefinition ce, bool isStatic) { //var list = new List<IField>(); foreach (var pe in ce.GetProperties(t => t.IsStatic == isStatic, GetMemberOptions.IgnoreInheritedMembers)) { if (!JMeta.IsJsExported(pe)) { continue; } if (JMeta.IsNativeField(pe)) { yield return(GenerateFakeField(pe)); } else if (pe.IsAutomaticProperty(Compiler.Project)) { yield return(GenerateBackingField(pe)); } } //return list; }
public virtual List <JEntityDeclaration> _VisitEnum(ITypeDefinition ce) { var unit = new JUnit { Statements = new List <JStatement>() }; ExportTypeNamespace(ce); var att = ce.GetMetadata <JEnumAttribute>(); bool valuesAsNames; JMeta.UseJsonEnums(ce, out valuesAsNames); //var valuesAsNames = att != null && att.ValuesAsNames; var constants = ce.GetConstants().ToList(); if (!valuesAsNames && constants.Where(t => t.ConstantValue == null).FirstOrDefault() != null) { var value = 0L; foreach (var c in constants) { if (c.ConstantValue == null) { c.SetConstantValue(value); } else { value = Convert.ToInt64(c.ConstantValue); } value++; } } constants.RemoveAll(t => !JMeta.IsJsExported(t)); var json = new JJsonObjectExpression { NamesValues = new List <JJsonNameValue>() }; json.NamesValues.AddRange(constants.Select(t => Export(t, valuesAsNames))); var st = ce.JAccess().Assign(json).Statement(); unit.Statements.Add(st); throw new NotSupportedException(); }
void TransformIntoBaseMethodCallIfNeeded(CSharpInvocationResolveResult res, JInvocationExpression node2) { var target = res.TargetResult as ThisResolveResult; if (target != null && target.CausesNonVirtualInvocation) //base. { //var info = res.GetInfo(); //var node = info.Nodes.FirstOrDefault(); var ce = target.Type;// node.FindThisEntity(); if (ce != null && JMeta.IsExtJsType(ce.GetDefinitionOrArrayType(Compiler))) { node2.Member = J.This().Member("callParent"); if (node2.Arguments.IsNotNullOrEmpty()) { node2.Arguments = new List <JExpression> { J.NewJsonArray(node2.Arguments.ToArray()) } } ; //var me2 = (node2.Member as JsMemberExpression); //me2.Name = "callParent"; return; } IMethod me2; var me = res.Member; if (me is IProperty) { me2 = ((IProperty)me).Getter; } else if (me is IMethod) { me2 = (IMethod)res.Member; } else { throw new Exception("Can't resolve method from member: " + res.Member); } ((JMemberExpression)node2.Member).PreviousMember = J.Member("super"); } }
protected List <IMethod> GetAccessorsToExport(IProperty pe) { var list = new List <IMethod>(); if (pe.IsAutomaticProperty(Compiler.Project) && !JMeta.IsNativeField(pe)) { list.Add(pe.Getter); list.Add(pe.Setter); } else { if (pe.Getter != null) { list.Add(pe.Getter); } if (pe.Setter != null) { list.Add(pe.Setter); } } list.RemoveAll(t => !JMeta.IsJsExported(t)); return(list); }
private JTypeImporter GetTypeImporter(ITypeDefinition ce) { JTypeImporter export; var isExtJs = JMeta.IsExtJsType(ce); var isGlobal = JMeta.IsGlobalType(ce) && !isExtJs; var isNative = JMeta.IsNativeType(ce) && !isExtJs; isNative = true; isGlobal = false; isExtJs = false; if (isGlobal) { throw new NotSupportedException(); } else if (isNative) { if (NativeExport == null) { NativeExport = new JTypeImporter { Compiler = Compiler } } ; export = NativeExport; } else if (isExtJs) { throw new NotSupportedException(); } else { throw new NotSupportedException(); } ConfigureTypeExport(export); return(export); }
private JNode VisitInvocationResolveResult(CSharpInvocationResolveResult res) { ////TODO: LET LINQ //var firstNode = res.GetFirstNode(); //if (firstNode != null && firstNode is QueryLetClause) //{ // foreach (var arg in res.Arguments) // { // if (arg.GetInfo() == null) // arg.SetInfo(new ResolveResultInfo { Nodes = { firstNode } }); // } //} var member = res.Member; var me = member as IMethod; if (me == null) { var pe = member as IProperty; if (pe != null) { me = pe.Getter; member = me; } } var att = me != null?JMeta.GetJMethodAttribute(me) : null; if (att != null && att.InlineCode != null) { return(J.Code(att.InlineCode)); } //TODO: move defines locally var condAtt = me.GetMetadata <System.Diagnostics.ConditionalAttribute>(); if (condAtt != null && Compiler != null && Compiler.Defines != null && !Compiler.Defines.Contains(condAtt.ConditionString)) { return(null); } if (att != null && att.OmitCalls) { if (me.IsStatic() && !me.IsExtensionMethod) { return(null); } if (me.IsExtensionMethod && !res.IsExtensionMethodInvocation) { return(null); } if (res.Arguments.IsEmpty() && res.TargetResult != null) { return(VisitExpression(res.TargetResult)); } return(Visit(res.Arguments[0])); } var jsMember = JNaming.JAccess(member); if (res.TargetResult != null && !member.IsStatic() && member.SymbolKind != SymbolKind.Constructor) //TargetResult==null when ctor { var target = VisitExpression(res.TargetResult); if (jsMember.PreviousMember != null) { throw new NotSupportedException(); } jsMember.PreviousMember = target; } var bindings = res.GetArgumentsForCall2(); if (JMeta.OmitOptionalParameters(me)) { bindings.RemoveAll(t => t.ArgResult == null); } if (JMeta.IsNativeParams(me)) { var binding = bindings.Where(t => t.Parameter.IsParams).FirstOrDefault(); if (binding != null) { if (binding.CallResult is ArrayCreateResolveResult) { var arrayRes = (ArrayCreateResolveResult)binding.CallResult; bindings.Remove(binding); if (arrayRes.InitializerElements.IsNotNullOrEmpty()) { foreach (var init in arrayRes.InitializerElements) { var b = binding.Clone(); b.CallResult = init; bindings.Add(b); } } } else { Log.Warn(res.GetFirstNode(), "Invalid params parameter passed to method with NativeParams=true"); } } } var byRefs = new List <ByReferenceResolveResult>(); List <int> refToRefs = new List <int>(); var c = 0; foreach (var binding in bindings) { var byRef = binding.CallResult as ByReferenceResolveResult; if (byRef == null) { c++; continue; } var x = byRef.ElementResult as LocalResolveResult; if (x != null && x.Variable != null && x.Variable.Type.Kind == TypeKind.ByReference) { if (binding.Parameter.IsRef || binding.Parameter.IsOut) { refToRefs.Add(c); } c++; continue; } byRefs.Add(byRef); c++; } var callArgs = bindings.Select(t => t.CallResult).ToList(); var node2 = new JInvocationExpression { Member = jsMember, Arguments = VisitExpressions(callArgs), }; foreach (var i in refToRefs) { JMemberExpression jsmex = node2.Arguments[i] as JMemberExpression; if (jsmex != null) { node2.Arguments[i] = jsmex.PreviousMember;//remove the .Value ref wrapper } } if (me != null && me.IsExtensionMethod && res.IsExtensionMethodInvocation && JMeta.ExtensionImplementedInInstance(me)) { var arg = node2.Arguments[0]; node2.Arguments.RemoveAt(0); if (jsMember.PreviousMember != null) { throw new NotImplementedException(); } jsMember.PreviousMember = arg; } TransformIntoBaseMethodCallIfNeeded(res, node2); if (att != null) { if (att.OmitParanthesis) { node2.OmitParanthesis = true; } if (node2.Arguments == null) { node2.Arguments = new List <JExpression>(); } if (att.InsertArg2 != null) { node2.Arguments.InsertOrAdd(2, new JCodeExpression { Code = att.InsertArg2.ToString() }); } if (att.InsertArg1 != null) { node2.Arguments.InsertOrAdd(1, new JCodeExpression { Code = att.InsertArg1.ToString() }); } if (att.InsertArg0 != null) { node2.Arguments.InsertOrAdd(0, new JCodeExpression { Code = att.InsertArg0.ToString() }); } node2.OmitCommas = att.OmitCommas; node2.ArgumentsPrefix = att.ArgumentsPrefix; node2.ArgumentsSuffix = att.ArgumentsSuffix; if (att.InstanceImplementedAsExtension) { var ext = (JMemberExpression)node2.Member; node2.Arguments.Insert(0, ext.PreviousMember); ext.PreviousMember = null; } } //if (me != null && me is SpecializedMethod && !Sk.IgnoreGenericMethodArguments(me)) //{ // List<JsExpression> genericArgs; // if (me.IsConstructor) // { // var ce = me.DeclaringType as ParameterizedType; // if (ce != null) // genericArgs = ce.TypeArguments.Select(t => SkJs.EntityTypeRefToMember(t, true)).ToList(); // else // genericArgs = new List<JsExpression>(); // } // else // { // var sme = (SpecializedMethod)me; // genericArgs = sme.TypeArguments.Select(t => SkJs.EntityTypeRefToMember(t, true)).ToList(); // } // if (node2.Arguments == null) // node2.Arguments = new List<JsExpression>(genericArgs); // else // node2.Arguments.InsertRange(0, genericArgs); //} if (att != null && att.OmitDotOperator) { if (node2.Member is JMemberExpression && node2.Arguments.Count == 1 && att.OmitParanthesis) { var meNode = (JMemberExpression)node2.Member; var node3 = new JBinaryExpression { Left = meNode.PreviousMember, Operator = meNode.Name, Right = node2.Arguments[0] }; return(node3); } else { Log.Warn(res.GetFirstNode(), "TODO:OmitDotOperator is not supported in this syntax."); } } if (node2.Member is JMemberExpression) { var x = (JMemberExpression)node2.Member; if (x.Name.IsNullOrEmpty() && jsMember.PreviousMember != null) { node2.Member = x.PreviousMember; } } if (res.Member.SymbolKind == SymbolKind.Indexer && JMeta.UseNativeIndexer((IProperty)res.Member)) { var node3 = new JIndexerAccessExpression { Member = node2.Member, Arguments = node2.Arguments, }; return(node3); } if (byRefs.IsNotNullOrEmpty()) { var func = J.Function(); foreach (var byRef in byRefs) { func.Add(J.Assign(VisitExpression(byRef), J.Json().Add("Value", VisitExpression(byRef))).Statement()); } func.Add(J.Var("$res", res.Type.JAccess(), node2).Statement()); foreach (var byRef in byRefs) { func.Add(J.Assign(VisitExpression(byRef), VisitExpression(byRef).Member("Value")).Statement()); } func.Add(J.Return(J.Member("$res"))); var node5 = WrapFunctionAndInvoke(res, func.Block); return(node5); } return(node2); }
private JNode VisitConversion(ResolveResult input, Conversion conversion, IType conversionType) { ////TODO: HACK: https://github.com/icsharpcode/NRefactory/issues/183 //var isImplicit = res.Conversion.IsImplicit; //if (!isImplicit && res.Conversion.IsExplicit && res.Conversion.Method != null && res.Conversion.Method.Name != null && res.Conversion.Method.Name.Contains("Implicit")) // isImplicit = true; if (conversion.IsMethodGroupConversion) { var me = conversion.Method; var delType = conversionType; var exp = me.JAccess().Invoke(me.Parameters.Select(t => J.Member(t.Name)).ToArray()); var st = J.Return(exp); var block = J.Block().Add(st); var del2 = CreateDelegate(delType, me.Parameters, me.ReturnType, block); return(del2); //J.CreateDelegate(conversionType.JAccess(), me.Parameters.Select(t=>t.Acc //TODO: J.CreateDelegate(conversionType.JAccess(), } else if (conversion.IsUserDefined) { ITypeDefinition typeDef; if (conversion.Method != null && conversion.Method.DeclaringType != null) { typeDef = conversion.Method.DeclaringType.GetDefinitionOrArrayType(Compiler); } else { typeDef = conversionType.GetDefinitionOrArrayType(Compiler); } var nativeOverloads = JMeta.UseNativeOperatorOverloads(typeDef); if (nativeOverloads) { return(Visit(input)); } var fake = conversion.Method.InvokeMethod(null, input); var node2 = Visit(fake); return(node2); } else if (conversion.IsTryCast || conversion.IsExplicit) { var typeDef = conversionType.GetDefinitionOrArrayType(Compiler); var omitCasts = JMeta.OmitCasts(typeDef, Project); if (omitCasts) { return(Visit(input)); } if (true)//Sk.NativeCasts(typeDef)) { var exp2 = VisitExpression(input); var type2 = JNaming.JAccess(conversionType); if (conversion.IsTryCast) { var node2 = exp2.InstanceOf(type2).Conditional(exp2, J.Null()); return(node2); } else { return(J.Cast(exp2, type2)); } } //else //{ // var cast = conversion.IsTryCast ? "As" : "Cast"; // var node2 = J.Member(cast).Invoke(VisitExpression(input), JNaming.JAccess(conversionType)); // return node2; //} } return(Visit(input)); }
public JNode VisitOperatorResolveResult(OperatorResolveResult res) { if (res.Operands.Count == 1) { if (res.UserDefinedOperatorMethod != null && !JMeta.UseNativeOperatorOverloads(res.UserDefinedOperatorMethod.DeclaringTypeDefinition)) { var fake = Cs.InvokeMethod(res.UserDefinedOperatorMethod, null, res.Operands[0]); return(Visit(fake)); } var isProperty = false; var meRes = res.Operands[0] as MemberResolveResult; if (meRes != null && meRes.Member != null && IsEntityFunctionProperty(meRes.Member, res)) { isProperty = true; } JExpression node2; if (res.OperatorType == System.Linq.Expressions.ExpressionType.Negate || res.OperatorType == System.Linq.Expressions.ExpressionType.PreDecrementAssign || res.OperatorType == System.Linq.Expressions.ExpressionType.PreIncrementAssign || res.OperatorType == System.Linq.Expressions.ExpressionType.Not || res.OperatorType == System.Linq.Expressions.ExpressionType.OnesComplement) { var simpler = res.OperatorType.ExtractCompoundAssignment(); if (isProperty && simpler != null) { var fakeCs = meRes.Member.AccessSelf().Binary(simpler.Value, Cs.Value(1, Project), meRes.Type); node2 = VisitExpression(fakeCs); } else { node2 = new JPreUnaryExpression { Operator = Visit(res.OperatorType), Right = VisitExpression(res.Operands[0]) }; } } else if (res.OperatorType == System.Linq.Expressions.ExpressionType.PostIncrementAssign || res.OperatorType == System.Linq.Expressions.ExpressionType.PostDecrementAssign || res.OperatorType == System.Linq.Expressions.ExpressionType.PreIncrementAssign || res.OperatorType == System.Linq.Expressions.ExpressionType.PreDecrementAssign) { if (isProperty) { var simpler = res.OperatorType.ExtractCompoundAssignment(); var fakeCs = meRes.Member.AccessSelf().Binary(simpler.Value, Cs.Value(1, Project), meRes.Type); node2 = VisitExpression(fakeCs); } else { node2 = new JPostUnaryExpression { Operator = Visit(res.OperatorType), Left = VisitExpression(res.Operands[0]) }; } } else { throw new NotImplementedException(); } return(node2); } else if (res.Operands.Count == 2) { if (res.UserDefinedOperatorMethod != null && !JMeta.UseNativeOperatorOverloads(res.UserDefinedOperatorMethod.DeclaringTypeDefinition)) { var fake = Cs.InvokeMethod(res.UserDefinedOperatorMethod, null, res.Operands[0], res.Operands[1]); return(Visit(fake)); } if (res.OperatorType == System.Linq.Expressions.ExpressionType.Coalesce) { var fake = Cs.Conditional(res.Operands[0].NotEqual(Cs.Null(), Project), res.Operands[0], res.Operands[1], res.Type); var fake2 = Visit(fake); fake2 = new JParenthesizedExpression { Expression = (JExpression)fake2 }; return(fake2); } var mrrOp0 = res.Operands[0] as MemberResolveResult; if (mrrOp0 != null && mrrOp0.Member.SymbolKind == SymbolKind.Event) { var pe = (IEvent)mrrOp0.Member; if (res.OperatorType == System.Linq.Expressions.ExpressionType.AddAssign || res.OperatorType == System.Linq.Expressions.ExpressionType.SubtractAssign) { var accessor = res.OperatorType == System.Linq.Expressions.ExpressionType.AddAssign ? pe.AddAccessor : pe.RemoveAccessor; var fake = new CSharpInvocationResolveResult(mrrOp0.TargetResult, accessor, new List <ResolveResult> { res.Operands[1] }); var node6 = Visit(fake); return(node6); } } if (mrrOp0 != null && IsEntityFunctionProperty(mrrOp0.Member, res)) { var compOpType = res.OperatorType.ExtractCompoundAssignment(); var pe = (IProperty)mrrOp0.Member; if (compOpType != null) { var fake = new CSharpInvocationResolveResult(mrrOp0.TargetResult, pe.Setter, new List <ResolveResult> { new OperatorResolveResult(res.Type, compOpType.Value, new CSharpInvocationResolveResult(mrrOp0.TargetResult, pe.Getter, null), res.Operands[1]) }); var node6 = Visit(fake); return(node6); } else if (res.OperatorType == System.Linq.Expressions.ExpressionType.Assign) { var args = new List <ResolveResult>(); if (pe.IsIndexer) { var irrOp0 = (CSharpInvocationResolveResult)res.Operands[0]; args.AddRange(irrOp0.Arguments); } args.Add(res.Operands[1]); var fake = new CSharpInvocationResolveResult(mrrOp0.TargetResult, pe.Setter, args).AssociateWithOriginal(res); var node6 = Visit(fake); node6 = WrapSetterToReturnValueIfNeeded(res, node6); return(node6); } } if (res.Operands[0] is ConversionResolveResult && res.Operands[1] is ConstantResolveResult) { var leftConv = (ConversionResolveResult)res.Operands[0]; var rightConst = (ConstantResolveResult)res.Operands[1]; if (leftConv.Conversion.IsNumericConversion && leftConv.Input.Type == Cs.CharType(Project)) { var value = ((char)(int)rightConst.ConstantValue).ToString(); var fake = Cs.Binary(leftConv.Input, res.OperatorType, Cs.Value(value, Project), leftConv.Input.Type); return(Visit(fake)); } } if (res.Operands[0].Type.Kind == TypeKind.Delegate && res.Operands[1].Type.Kind == TypeKind.Delegate) { if (res.OperatorType == System.Linq.Expressions.ExpressionType.AddAssign || res.OperatorType == System.Linq.Expressions.ExpressionType.SubtractAssign) { var op = res.OperatorType == System.Linq.Expressions.ExpressionType.AddAssign ? System.Linq.Expressions.ExpressionType.Add : System.Linq.Expressions.ExpressionType.Subtract; var fake = Cs.Assign(res.Operands[0], Cs.Binary(res.Operands[0], op, res.Operands[1], res.Type)); var node6 = Visit(fake); return(node6); } else if (res.OperatorType == System.Linq.Expressions.ExpressionType.Add || res.OperatorType == System.Linq.Expressions.ExpressionType.Subtract) { var combineMethod = Compiler.Project.Compilation.FindType(KnownTypeCode.Delegate).GetMethods(t => t.Name == "Combine").FirstOrDefault(); var removeMethod = Compiler.Project.Compilation.FindType(KnownTypeCode.Delegate).GetMethods(t => t.Name == "Remove").FirstOrDefault(); var meOp = res.OperatorType == System.Linq.Expressions.ExpressionType.Add ? combineMethod : removeMethod; var fake = Cs.Member(null, meOp).Invoke(res.Operands[0], res.Operands[1]); var node6 = Visit(fake); return(node6); } } var node5 = new JBinaryExpression { Operator = Visit(res.OperatorType), Left = VisitExpression(res.Operands[0]), Right = VisitExpression(res.Operands[1]) }; if (res.OperatorType == System.Linq.Expressions.ExpressionType.Equal && node5.Operator == "==") { var att = JMeta.GetJsExportAttribute(Project.Compilation.MainAssembly); if (att != null && att.UseExactEquals) { node5.Operator = "==="; } } if (res.OperatorType == System.Linq.Expressions.ExpressionType.NotEqual && node5.Operator == "!=") { var att = JMeta.GetJsExportAttribute(Project.Compilation.MainAssembly); if (att != null && att.UseExactEquals) { node5.Operator = "!=="; } } return(node5); } else if (res.Operands.Count == 3) { if (res.OperatorType == System.Linq.Expressions.ExpressionType.Conditional) { var node5 = new JConditionalExpression { Condition = VisitExpression(res.Operands[0]), TrueExpression = VisitExpression(res.Operands[1]), FalseExpression = VisitExpression(res.Operands[2]) }; return(node5); } else { throw new NotImplementedException(); } } else { throw new NotImplementedException(); } }
private JNode VisitInvocationResolveResultAsCtor(CSharpInvocationResolveResult res) { if (res.Type.Kind == TypeKind.Delegate) { return(Visit(res.Arguments.Single())); } var me = (IMethod)res.Member; var meAtt = JMeta.GetJMethodAttribute(me); var ce = me.GetDeclaringTypeDefinition(); var att = ce == null ? null : ce.GetJsTypeAttribute(); if (att != null && att.Mode == JsMode.Json && (meAtt == null || meAtt.Name == null)) { var node2 = VisitInvocationResolveResult(res); var json = InitializersToJson(res.InitializerStatements, res.Type); return(json); } else { var invokeExp = (JInvocationExpression)VisitInvocationResolveResult(res); var newExp = new JNewObjectExpression { Invocation = invokeExp }; JExpression finalExp; if (meAtt != null && meAtt.OmitNewOperator) { finalExp = invokeExp; } else { finalExp = newExp; } if (meAtt != null && meAtt.JsonInitializers) { var json = InitializersToJson(res.InitializerStatements, res.Type); invokeExp.Arguments.Add(json); } else if (res.InitializerStatements.IsNotNullOrEmpty()) { //var func = J.Function(); var func = J.Block(); var inits2 = res.InitializerStatements.Select(t => Visit(t)).ToList(); var init1 = res.InitializerStatements[0]; var target = FindInitializedObjectResolveResult(res);// ((init1 as OperatorResolveResult).Operands[0] as MemberResolveResult).TargetResult as InitializedObjectResolveResult; var varName = Initializers[target]; func.Add(J.Var(varName, res.Type.JAccess(), finalExp).Statement()); foreach (var init in inits2) { var exp = ((JExpression)init); func.Add(exp.Statement()); } func.Add(J.Return(J.Member(varName))); finalExp = WrapFunctionAndInvoke(res, func); } return(finalExp); } }
public JNode VisitMethodGroupResolveResult(MethodGroupResolveResult res) { var info = res.GetInfo(); IMethod me; if (info != null && info.Conversion != null && info.Conversion.Method != null) { me = info.Conversion.Method; } else //happens when invoking a method with overloads, and a parameter is dynamic { var list = res.Methods.ToList(); if (list.Count == 0) { throw new Exception("Method group not resolved to any method"); } else if (list.Count == 1) { me = list[0]; } else { me = list[0]; } //TODO: verify all methods has the same js name } var isExtensionMethodStyle = me.IsExtensionMethod && !(res.TargetResult is TypeResolveResult);//TODO: IsExtensionMethodStyle(new CsInvocationExpression { entity = me, expression = node }); JExpression firstPrm = null; if (isExtensionMethodStyle) { firstPrm = (JExpression)Visit(res.TargetResult); } var node2 = JNaming.JAccess(me); JExpression node3; JExpression instanceContext = null; if (me.IsStatic || res.TargetResult == null) //getting ThisResolveResult even on static methods, getting TargetResult=null when MethodGroupResolveResult when using delegates { node3 = node2; } else { instanceContext = VisitExpression(res.TargetResult); node3 = instanceContext.Member(node2); } if (info != null && (instanceContext != null || firstPrm != null)) { var conv = info.Conversion; if (info.ConversionTargetType != null && !UseNativeFunctions(info.ConversionTargetType))//delegate type { var parentMethod = info.Nodes.FirstOrDefault().GetCurrentMethod(); if (parentMethod == null || !JMeta.ForceDelegatesAsNativeFunctions(parentMethod)) { if (parentMethod == null) { Log.Warn(info.Nodes.FirstOrDefault(), "GetParentMethod() returned null"); } var func = (JExpression)node2; if (instanceContext != null) { node3 = CreateJsDelegate(instanceContext, func); } else if (firstPrm != null) { node3 = CreateJsExtensionDelegate(firstPrm, func); } } } } return(node3); }
//JsTypeImporter_ExtJs ExtJsExport; private bool ShouldExportType(ITypeDefinition ce) { return(JMeta.IsJsExported(ce)); }
public JNode VisitForeachStatement_old(ForeachStatement node) { if (node.InExpression != null) { var expRes = node.InExpression.Resolve(); var et = expRes.Type.GetDefinitionOrArrayType(Compiler); var iteratorType = expRes.Type; //var et = node.expression.entity_typeref.GetEntityType(); if (et != null) { var jta = JMeta.GetJsTypeAttribute(et); if (jta != null && jta.NativeEnumerator) { var node2 = new JForInStatement { Initializer = J.Var(node.VariableName, node.Resolve().Type.JAccess()), Member = VisitExpression(node.InExpression), Statement = VisitStatement(node.EmbeddedStatement) }; return(node2); } else if (jta != null && jta.NativeArrayEnumerator) { VariableIteratorCounter++; var iteratorName = "$i" + VariableIteratorCounter; var lengthCacheName = "$l" + VariableIteratorCounter; var exp2 = VisitExpression(node.InExpression); var target = exp2; var targetCacheName = "$t" + VariableIteratorCounter; if (exp2 is JMemberExpression || ((JMemberExpression)exp2).PreviousMember != null)//is not simple name { target = J.Member(targetCacheName); } var itemAccess = target.IndexerAccess(J.Member(iteratorName)); var node2 = new JForStatement(); node2.Condition = J.Member(iteratorName).LessThan(J.Member(lengthCacheName)); node2.Iterators = new List <JStatement> { J.Member(iteratorName).PlusPlus().Statement(), J.Member(node.VariableName).Assign(itemAccess).Statement() }; if (target != exp2)//use target caching { node2.Initializers = new List <JStatement> { J.Var(iteratorName, iteratorType.JAccess(), J.Value(0)).AndVar(targetCacheName, exp2).AndVar(lengthCacheName, target.Member("length")).AndVar(node.VariableName, itemAccess).Statement() }; } else { node2.Initializers = new List <JStatement> { J.Var(iteratorName, iteratorType.JAccess(), J.Value(0)).AndVar(lengthCacheName, exp2.Member("length")).AndVar(node.VariableName, itemAccess).Statement() }; } node2.Statement = VisitStatement(node.EmbeddedStatement); return(node2); } } } var iteratorName2 = "$it" + VariableIteratorCounter; VariableIteratorCounter++; var node3 = J.Var(iteratorName2, node.Resolve().Type.JAccess(), VisitExpression(node.InExpression).Member("GetEnumerator").Invoke()).Statement(); var whileNode = J.While(J.Member(iteratorName2).Member("MoveNext").Invoke()); var getCurrentStatement = J.Var(node.VariableName, node.Resolve().Type.JAccess(), J.Member(iteratorName2).Member("get_Current").Invoke()).Statement(); var jsStatement = VisitStatement(node.EmbeddedStatement); JBlock block; if (jsStatement is JBlock) { block = (JBlock)jsStatement; } else { block = J.Block().Add(jsStatement); } block.Statements.Insert(0, getCurrentStatement); whileNode.Statement = block; var block2 = J.Block().Add(node3).Add(whileNode); return(block2); }