Пример #1
0
 public string[] PreCallback(CodeGenerationOptions opt, string var_name, bool owned)
 {
     return(new string[] { String.Format("global::Java.Lang.ICharSequence {0} = global::Java.Lang.Object.GetObject<global::Java.Lang.ICharSequence> ({1}, JniHandleOwnership.DoNotTransfer);", var_name, SymbolTable.GetNativeName(var_name)) });
 }
 public string[] PostCallback(CodeGenerationOptions opt, string var_name)
 {
     return(new string [0]);
 }
 public string[] PreCallback(CodeGenerationOptions opt, string var_name, bool owned)
 {
     return(new string[] { String.Format("var {0} = global::Android.Runtime.XmlPullParserReader.FromJniHandle ({1}, JniHandleOwnership.DoNotTransfer);", opt.GetSafeIdentifier(var_name), opt.GetSafeIdentifier(TypeNameUtilities.GetNativeName(var_name))) });
 }
 public string FromNative(CodeGenerationOptions opt, string var_name, bool owned)
 {
     return(String.Format(opt.GetOutputName("Android.Runtime.XmlPullParserReader") + ".FromJniHandle ({0}, {1})", var_name, owned ? "JniHandleOwnership.TransferLocalRef" : "JniHandleOwnership.DoNotTransfer"));
 }
 public bool Validate(CodeGenerationOptions opt, GenericParameterDefinitionList type_params, CodeGeneratorContext context)
 {
     return(true);
 }
Пример #6
0
		public string FromNative (CodeGenerationOptions opt, string varname, bool owned)
		{
			return String.Format ("({0}) {1}", opt.GetOutputName (type), varname);
		}
Пример #7
0
		public string[] PreCallback (CodeGenerationOptions opt, string var_name, bool owned)
		{
			throw new NotSupportedException (string.Format ("{0} does not support PreCallback", this.GetType ().Name));
		}
Пример #8
0
 public void Generate(GenBase gen, StreamWriter sw, string indent, CodeGenerationOptions opt)
 {
     Generate(gen, sw, indent, opt, true, false);
 }
Пример #9
0
        public void Generate(GenBase gen, StreamWriter sw, string indent, CodeGenerationOptions opt, bool with_callbacks, bool force_override)
        {
            // <TechnicalDebt>
            // This is a special workaround for AdapterView inheritance.
            // (How it is special? They have hand-written bindings AND brings generic
            // version of AdapterView<T> in the inheritance, also added by metadata!)
            //
            // They are on top of fragile hand-bound code, and when we are making changes
            // in generator, they bite. Since we are not going to bring API breakage
            // right now, we need special workarounds to get things working.
            //
            // So far, what we need here is to have AbsSpinner.Adapter compile.
            //
            // > platforms/*/src/generated/Android.Widget.AbsSpinner.cs(156,56): error CS0533:
            // > `Android.Widget.AbsSpinner.Adapter' hides inherited abstract member
            // > `Android.Widget.AdapterView<Android.Widget.ISpinnerAdapter>.Adapter
            //
            // It is because the AdapterView<T>.Adapter is hand-bound and cannot be
            // detected by generator!
            //
            // So, we explicitly treat it as a special-case.
            //
            // Then, Spinner, ListView and GridView instantiate them, so they are also special cases.
            // </TechnicalDebt>
            if (Name == "Adapter" &&
                (Getter.DeclaringType.BaseGen.FullName == "Android.Widget.AdapterView" ||
                 Getter.DeclaringType.BaseGen.BaseGen != null && Getter.DeclaringType.BaseGen.BaseGen.FullName == "Android.Widget.AdapterView"))
            {
                force_override = true;
            }
            // ... and the above breaks generator tests...
            if (Name == "Adapter" &&
                (Getter.DeclaringType.BaseGen.FullName == "Xamarin.Test.AdapterView" ||
                 Getter.DeclaringType.BaseGen.BaseGen != null && Getter.DeclaringType.BaseGen.BaseGen.FullName == "Xamarin.Test.AdapterView"))
            {
                force_override = true;
            }

            string decl_name        = AdjustedName;
            string needNew          = gen.RequiresNew(decl_name) ? " new" : "";
            string virtual_override = String.Empty;
            bool   is_virtual       = Getter.IsVirtual && (Setter == null || Setter.IsVirtual);

            if (with_callbacks && is_virtual)
            {
                virtual_override = needNew + " virtual";
                opt.CodeGenerator.WriteMethodCallback(Getter, sw, indent, opt, gen, AdjustedName);
            }
            if (with_callbacks && is_virtual && Setter != null)
            {
                virtual_override = needNew + " virtual";
                opt.CodeGenerator.WriteMethodCallback(Setter, sw, indent, opt, gen, AdjustedName);
            }
            virtual_override = force_override ? " override" : virtual_override;
            if ((Getter ?? Setter).IsStatic)
            {
                virtual_override = " static";
            }
            // It should be using AdjustedName instead of Name, but ICharSequence ("Formatted") properties are not caught by this...
            else if (gen.BaseSymbol != null && gen.BaseSymbol.GetPropertyByName(Name, true) != null)
            {
                virtual_override = " override";
            }

            opt.CodeGenerator.WriteMethodIdField(Getter, sw, indent, opt);
            if (Setter != null)
            {
                opt.CodeGenerator.WriteMethodIdField(Setter, sw, indent, opt);
            }
            string visibility = Getter.IsAbstract && Getter.RetVal.IsGeneric ? "protected" : (Setter ?? Getter).Visibility;

            // Unlike [Register], mcs does not allow applying [Obsolete] on property accessors, so we can apply them only under limited condition...
            if (Getter.Deprecated != null && (Setter == null || Setter.Deprecated != null))
            {
                sw.WriteLine("{0}[Obsolete (@\"{1}\")]", indent, Getter.Deprecated.Replace("\"", "\"\"").Trim() + (Setter != null && Setter.Deprecated != Getter.Deprecated ? " " + Setter.Deprecated.Replace("\"", "\"\"").Trim() : null));
            }
            opt.CodeGenerator.WriteMethodCustomAttributes(Getter, sw, indent);
            sw.WriteLine("{0}{1}{2} unsafe {3} {4} {{", indent, visibility, virtual_override, opt.GetOutputName(Getter.ReturnType), decl_name);
            if (gen.IsGeneratable)
            {
                sw.WriteLine("{0}\t// Metadata.xml XPath method reference: path=\"{1}/method[@name='{2}'{3}]\"", indent, gen.MetadataXPathReference, Getter.JavaName, Getter.Parameters.GetMethodXPathPredicate());
            }
            sw.WriteLine("{0}\t[Register (\"{1}\", \"{2}\", \"{3}\"{4})]", indent, Getter.JavaName, Getter.JniSignature, Getter.ConnectorName, Getter.AdditionalAttributeString());
            sw.WriteLine("{0}\tget {{", indent);
            opt.CodeGenerator.WriteMethodBody(Getter, sw, indent + "\t\t", opt);
            sw.WriteLine("{0}\t}}", indent);
            if (Setter != null)
            {
                if (gen.IsGeneratable)
                {
                    sw.WriteLine("{0}\t// Metadata.xml XPath method reference: path=\"{1}/method[@name='{2}'{3}]\"", indent, gen.MetadataXPathReference, Setter.JavaName, Setter.Parameters.GetMethodXPathPredicate());
                }
                opt.CodeGenerator.WriteMethodCustomAttributes(Setter, sw, indent);
                sw.WriteLine("{0}\t[Register (\"{1}\", \"{2}\", \"{3}\"{4})]", indent, Setter.JavaName, Setter.JniSignature, Setter.ConnectorName, Setter.AdditionalAttributeString());
                sw.WriteLine("{0}\tset {{", indent);
                string pname = Setter.Parameters [0].Name;
                Setter.Parameters [0].Name = "value";
                opt.CodeGenerator.WriteMethodBody(Setter, sw, indent + "\t\t", opt);
                Setter.Parameters [0].Name = pname;
                sw.WriteLine("{0}\t}}", indent);
            }
            else if (GenerateDispatchingSetter)
            {
                sw.WriteLine("{0}// This is a dispatching setter", indent + "\t");
                sw.WriteLine("{0}set {{ Set{1} (value); }}", indent + "\t", Name);
            }
            sw.WriteLine("{0}}}", indent);
            sw.WriteLine();

            if (Type.StartsWith("Java.Lang.ICharSequence") && virtual_override != " override")
            {
                GenerateStringVariant(sw, indent);
            }
        }
Пример #10
0
 public string Call(CodeGenerationOptions opt, string var_name) => opt.GetSafeIdentifier(var_name);
Пример #11
0
 public abstract string FromNative(CodeGenerationOptions opt, string varname, bool owned);
Пример #12
0
 public bool Validate(CodeGenerationOptions opt, GenericParameterDefinitionList type_params, CodeGeneratorContext context)
 {
     return(parms == null || parms.Validate(opt, type_params, context));
 }
Пример #13
0
 public string ToNative(CodeGenerationOptions opt, string varname, Dictionary <string, string> mappings = null)
 {
     return(string.Format("{0}.ToLocalJniHandle ({1})",
                          GetManagedTypeName(opt),
                          opt.GetSafeIdentifier(varname)));
 }
Пример #14
0
 public string[] PreCall(CodeGenerationOptions opt, string var_name)
 {
     return(new string[] { String.Format("IntPtr {0} = CharSequence.ToLocalJniHandle ({1});", opt.GetSafeIdentifier(SymbolTable.GetNativeName(var_name)), opt.GetSafeIdentifier(var_name)) });
 }
Пример #15
0
 public string FromNative(CodeGenerationOptions opt, string varname, bool owned)
 {
     return(String.Format("({0}) global::Java.Lang.Object.GetObject<{3}> ({1}, {2})", type, varname, owned ? "JniHandleOwnership.TransferLocalRef" : "JniHandleOwnership.DoNotTransfer", opt.GetOutputName(FullName)));
 }
Пример #16
0
 public void GenerateCallbacks(StreamWriter sw, string indent, CodeGenerationOptions opt, GenBase gen)
 {
     GenerateCallbacks(sw, indent, opt, gen, AdjustedName);
 }
Пример #17
0
 public JavaInteropCodeGenerator(TextWriter writer, CodeGenerationOptions options) : base(writer, options)
 {
 }
Пример #18
0
 public override string ToNative(CodeGenerationOptions opt, string varname, Dictionary <string, string> mappings = null)
 {
     return(String.Format("JNIEnv.ToLocalJniHandle ({0})", varname));
 }
Пример #19
0
		public string ToNative (CodeGenerationOptions opt, string varname, Dictionary<string, string> mappings = null)
		{
			return "(int) " + varname;
		}
Пример #20
0
        public override void Generate(StreamWriter sw, string indent, CodeGenerationOptions opt, GenerationInfo gen_info)
        {
            opt.ContextTypes.Push(this);
            opt.ContextGeneratedMethods = new List <Method> ();

            gen_info.TypeRegistrations.Add(new KeyValuePair <string, string>(RawJniName, AssemblyQualifiedName));
            bool is_enum = base_symbol != null && base_symbol.FullName == "Java.Lang.Enum";

            if (is_enum)
            {
                gen_info.Enums.Add(RawJniName.Replace('/', '.') + ":" + Namespace + ":" + JavaSimpleName);
            }
            StringBuilder sb = new StringBuilder();

            foreach (ISymbol isym in Interfaces)
            {
                GenericSymbol gs  = isym as GenericSymbol;
                InterfaceGen  gen = (gs == null ? isym : gs.Gen) as InterfaceGen;
                if (gen != null && gen.IsConstSugar)
                {
                    continue;
                }
                if (sb.Length > 0)
                {
                    sb.Append(", ");
                }
                sb.Append(opt.GetOutputName(isym.FullName));
            }

            string obj_type = null;

            if (base_symbol != null)
            {
                GenericSymbol gs = base_symbol as GenericSymbol;
                obj_type = gs != null && gs.IsConcrete ? gs.GetGenericType(null) : opt.GetOutputName(base_symbol.FullName);
            }

            sw.WriteLine("{0}// Metadata.xml XPath class reference: path=\"{1}\"", indent, MetadataXPathReference);

            if (this.IsDeprecated)
            {
                sw.WriteLine("{0}[ObsoleteAttribute (@\"{1}\")]", indent, this.DeprecatedComment);
            }
            sw.WriteLine("{0}[global::Android.Runtime.Register (\"{1}\", DoNotGenerateAcw=true{2})]", indent, RawJniName, this.AdditionalAttributeString());
            if (this.TypeParameters != null && this.TypeParameters.Any())
            {
                sw.WriteLine("{0}{1}", indent, TypeParameters.ToGeneratedAttributeString());
            }
            string inherits = "";

            if (inherits_object && obj_type != null)
            {
                inherits = ": " + obj_type;
            }
            if (sb.Length > 0)
            {
                if (string.IsNullOrEmpty(inherits))
                {
                    inherits = ": ";
                }
                else
                {
                    inherits += ", ";
                }
            }
            sw.WriteLine("{0}{1} {2}{3}{4}partial class {5} {6}{7} {{",
                         indent,
                         Visibility,
                         needs_new ? "new " : String.Empty,
                         IsAbstract ? "abstract " : String.Empty,
                         IsFinal ? "sealed " : String.Empty,
                         Name,
                         inherits,
                         sb.ToString());
            sw.WriteLine();

            var seen = new HashSet <string> ();

            GenFields(sw, indent + "\t", opt, seen);
            bool haveNested = false;

            foreach (var iface in GetAllImplementedInterfaces()
                     .Except(BaseGen == null
                                                ? new InterfaceGen[0]
                                                : BaseGen.GetAllImplementedInterfaces())
                     .Where(i => i.Fields.Count > 0))
            {
                if (!haveNested)
                {
                    sw.WriteLine();
                    sw.WriteLine("{0}\tpublic static class InterfaceConsts {{", indent);
                    haveNested = true;
                }
                sw.WriteLine();
                sw.WriteLine("{0}\t\t// The following are fields from: {1}", indent, iface.JavaName);
                iface.GenFields(sw, indent + "\t\t", opt, seen);
            }

            if (haveNested)
            {
                sw.WriteLine("{0}\t}}\n", indent);
            }

            foreach (GenBase nest in NestedTypes)
            {
                if (BaseGen != null && BaseGen.ContainsNestedType(nest))
                {
                    if (nest is ClassGen)
                    {
                        (nest as ClassGen).needs_new = true;
                    }
                }
                nest.Generate(sw, indent + "\t", opt, gen_info);
                sw.WriteLine();
            }

            bool requireNew = InheritsObject;

            if (!requireNew)
            {
                for (var bg = BaseGen; bg != null && bg is XmlClassGen; bg = bg.BaseGen)
                {
                    if (bg.InheritsObject)
                    {
                        requireNew = true;
                        break;
                    }
                }
            }
            opt.CodeGenerator.WriteClassHandle(this, sw, indent, opt, requireNew);

            GenConstructors(sw, indent + "\t", opt);

            GenProperties(sw, indent + "\t", opt);
            GenMethods(sw, indent + "\t", opt);

            if (IsAbstract)
            {
                GenerateAbstractMembers(sw, indent + "\t", opt);
            }

            bool is_char_seq = false;

            foreach (ISymbol isym in Interfaces)
            {
                if (isym is GenericSymbol)
                {
                    GenericSymbol gs = isym as GenericSymbol;
                    if (gs.IsConcrete)
                    {
                        // FIXME: not sure if excluding default methods is a valid idea...
                        foreach (Method m in gs.Gen.Methods.Where(m => !m.IsInterfaceDefaultMethod && !m.IsStatic))
                        {
                            if (m.IsGeneric)
                            {
                                m.GenerateExplicitIface(sw, indent + "\t", opt, gs);
                            }
                        }
                    }
                }
                else if (isym.FullName == "Java.Lang.ICharSequence")
                {
                    is_char_seq = true;
                }
            }

            if (is_char_seq)
            {
                GenCharSequenceEnumerator(sw, indent + "\t", opt);
            }

            sw.WriteLine(indent + "}");

            if (!AssemblyQualifiedName.Contains('/'))
            {
                foreach (InterfaceExtensionInfo nestedIface in GetNestedInterfaceTypes())
                {
                    nestedIface.Type.GenerateExtensionsDeclaration(sw, indent, opt, nestedIface.DeclaringType);
                }
            }

            if (IsAbstract)
            {
                sw.WriteLine();
                GenerateInvoker(sw, indent, opt);
            }

            opt.ContextGeneratedMethods.Clear();

            opt.ContextTypes.Pop();
        }
Пример #21
0
		public string[] PostCall (CodeGenerationOptions opt, string var_name)
		{
			throw new NotSupportedException (string.Format ("{0} does not support PostCall", this.GetType ().Name));
		}
Пример #22
0
 void GenerateInvoker(StreamWriter sw, IEnumerable <Property> properties, string indent, CodeGenerationOptions opt, HashSet <string> members)
 {
     foreach (Property prop in properties)
     {
         if (members.Contains(prop.Name))
         {
             continue;
         }
         members.Add(prop.Name);
         if ((prop.Getter != null && !prop.Getter.IsAbstract) ||
             (prop.Setter != null && !prop.Setter.IsAbstract))
         {
             continue;
         }
         prop.Generate(this, sw, indent, opt, false, true);
     }
 }
 public string ToNative(CodeGenerationOptions opt, string var_name, Dictionary <string, string> mappings = null)
 {
     return(String.Format("global::Android.Runtime.XmlReaderPullParser.ToLocalJniHandle ({0})", var_name));
 }
Пример #24
0
 void GenerateInvoker(StreamWriter sw, IEnumerable <Method> methods, string indent, CodeGenerationOptions opt, HashSet <string> members, InterfaceGen gen)
 {
     foreach (Method m in methods)
     {
         string sig = m.GetSignature();
         if (members.Contains(sig))
         {
             continue;
         }
         members.Add(sig);
         if (!m.IsAbstract)
         {
             continue;
         }
         if (IsExplicitlyImplementedMethod(sig))
         {
             // sw.WriteLine ("// This invoker explicitly implements this method");
             m.GenerateExplicitInterfaceInvoker(sw, indent, opt, gen);
         }
         else
         {
             // sw.WriteLine ("// This invoker overrides {0} method", gen.FullName);
             m.IsOverride = true;
             m.Generate(sw, indent, opt, this, false);
             m.IsOverride = false;
         }
     }
 }
 public string Call(CodeGenerationOptions opt, string var_name)
 {
     return(opt.GetSafeIdentifier(TypeNameUtilities.GetNativeName(var_name)));
 }
Пример #26
0
        public static void GenerateTypeRegistrations(CodeGenerationOptions opt, GenerationInfo gen_info)
        {
            StreamWriter sw = gen_info.Writer = gen_info.OpenStream(opt.GetFileName("Java.Interop.__TypeRegistrations"));

            Dictionary <string, List <KeyValuePair <string, string> > > mapping = new Dictionary <string, List <KeyValuePair <string, string> > >();

            foreach (KeyValuePair <string, string> reg in gen_info.TypeRegistrations)
            {
                int    ls      = reg.Key.LastIndexOf('/');
                string package = ls >= 0 ? reg.Key.Substring(0, ls) : "";

                if (JavaNativeTypeManager.ToCliType(reg.Key) == reg.Value)
                {
                    continue;
                }
                List <KeyValuePair <string, string> > v;
                if (!mapping.TryGetValue(package, out v))
                {
                    mapping.Add(package, v = new List <KeyValuePair <string, string> >());
                }
                v.Add(new KeyValuePair <string, string>(reg.Key, reg.Value));
            }

            sw.WriteLine("using System;");
            sw.WriteLine("using System.Collections.Generic;");
            sw.WriteLine("using Android.Runtime;");
            sw.WriteLine();
            sw.WriteLine("namespace Java.Interop {");
            sw.WriteLine();
            sw.WriteLine("\tpartial class __TypeRegistrations {");
            sw.WriteLine();
            sw.WriteLine("\t\tpublic static void RegisterPackages ()");
            sw.WriteLine("\t\t{");
            sw.WriteLine("#if MONODROID_TIMING");
            sw.WriteLine("\t\t\tvar start = DateTime.Now;");
            sw.WriteLine("\t\t\tAndroid.Util.Log.Info (\"MonoDroid-Timing\", \"RegisterPackages start: \" + (start - new DateTime (1970, 1, 1)).TotalMilliseconds);");
            sw.WriteLine("#endif // def MONODROID_TIMING");
            sw.WriteLine("\t\t\tJava.Interop.TypeManager.RegisterPackages (");
            sw.WriteLine("\t\t\t\t\tnew string[]{");
            foreach (KeyValuePair <string, List <KeyValuePair <string, string> > > e in mapping)
            {
                sw.WriteLine("\t\t\t\t\t\t\"{0}\",", e.Key);
            }
            sw.WriteLine("\t\t\t\t\t},");
            sw.WriteLine("\t\t\t\t\tnew Converter<string, Type>[]{");
            foreach (KeyValuePair <string, List <KeyValuePair <string, string> > > e in mapping)
            {
                sw.WriteLine("\t\t\t\t\t\tlookup_{0}_package,", e.Key.Replace('/', '_'));
            }
            sw.WriteLine("\t\t\t\t\t});");
            sw.WriteLine("#if MONODROID_TIMING");
            sw.WriteLine("\t\t\tvar end = DateTime.Now;");
            sw.WriteLine("\t\t\tAndroid.Util.Log.Info (\"MonoDroid-Timing\", \"RegisterPackages time: \" + (end - new DateTime (1970, 1, 1)).TotalMilliseconds + \" [elapsed: \" + (end - start).TotalMilliseconds + \" ms]\");");
            sw.WriteLine("#endif // def MONODROID_TIMING");
            sw.WriteLine("\t\t}");
            sw.WriteLine();
            sw.WriteLine("\t\tstatic Type Lookup (string[] mappings, string javaType)");
            sw.WriteLine("\t\t{");
            sw.WriteLine("\t\t\tstring managedType = Java.Interop.TypeManager.LookupTypeMapping (mappings, javaType);");
            sw.WriteLine("\t\t\tif (managedType == null)");
            sw.WriteLine("\t\t\t\treturn null;");
            sw.WriteLine("\t\t\treturn Type.GetType (managedType);");
            sw.WriteLine("\t\t}");
            foreach (KeyValuePair <string, List <KeyValuePair <string, string> > > map in mapping)
            {
                sw.WriteLine();
                string package = map.Key.Replace('/', '_');
                sw.WriteLine("\t\tstatic string[] package_{0}_mappings;", package);
                sw.WriteLine("\t\tstatic Type lookup_{0}_package (string klass)", package);
                sw.WriteLine("\t\t{");
                sw.WriteLine("\t\t\tif (package_{0}_mappings == null) {{", package);
                sw.WriteLine("\t\t\t\tpackage_{0}_mappings = new string[]{{", package);
                map.Value.Sort((a, b) => a.Key.CompareTo(b.Key));
                foreach (KeyValuePair <string, string> t in map.Value)
                {
                    sw.WriteLine("\t\t\t\t\t\"{0}:{1}\",", t.Key, t.Value);
                }
                sw.WriteLine("\t\t\t\t};");
                sw.WriteLine("\t\t\t}");
                sw.WriteLine("");
                sw.WriteLine("\t\t\treturn Lookup (package_{0}_mappings, klass);", package);
                sw.WriteLine("\t\t}");
            }
            sw.WriteLine("\t}");
            sw.WriteLine("}");
            sw.Close();
            gen_info.Writer = null;
        }
 public string[] PostCall(CodeGenerationOptions opt, string var_name)
 {
     return(new string [] {
         string.Format("JNIEnv.DeleteLocalRef ({0});", opt.GetSafeIdentifier(TypeNameUtilities.GetNativeName(var_name))),
     });
 }
Пример #28
0
 public string Call(CodeGenerationOptions opt, string var_name)
 {
     return(opt.GetSafeIdentifier(SymbolTable.GetNativeName(var_name)));
 }
 public string[] PreCall(CodeGenerationOptions opt, string var_name)
 {
     return(new string[] { String.Format("IntPtr {0} = global::Android.Runtime.XmlReaderPullParser.ToLocalJniHandle ({1});", opt.GetSafeIdentifier(TypeNameUtilities.GetNativeName(var_name)), opt.GetSafeIdentifier(var_name)) });
 }
Пример #30
0
 public string ToNative(CodeGenerationOptions opt, string var_name, Dictionary <string, string> mappings = null)
 {
     return(String.Format("CharSequence.ToLocalJniHandle ({0})", var_name));
 }