XQueryFunction.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. //
  2. // XQueryFunction.cs - XQuery 1.0 and XPath 2.0 Functions implementation
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. //
  8. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. //
  30. // See XQuery 1.0 and XPath 2.0 Functions and Operators.
  31. //
  32. #if NET_2_0
  33. using System;
  34. using System.Collections;
  35. using System.Reflection;
  36. using System.Xml;
  37. using System.Xml.Schema;
  38. using System.Xml.Query;
  39. using System.Xml.XPath;
  40. using System.Xml.Xsl;
  41. namespace Mono.Xml.XPath2
  42. {
  43. // It is instantiated per function definition. (e.g. fn:string(), fn:data(), fn:contat()).
  44. public abstract class XQueryFunction
  45. {
  46. public const string Namespace = "http://www.w3.org/2004/07/xpath-functions";
  47. static XQueryFunctionTable defaultFunctions = new XQueryFunctionTable ();
  48. static XQueryFunction ()
  49. {
  50. defaultFunctions.Add (FromName ("node-name", "FnNodeName"));
  51. defaultFunctions.Add (FromName ("nilled", "FnNilled"));
  52. defaultFunctions.Add (FromName ("string", "FnString"));
  53. defaultFunctions.Add (FromName ("data", "FnData"));
  54. defaultFunctions.Add (FromName ("base-uri", "FnBaseUri"));
  55. defaultFunctions.Add (FromName ("document-uri", "FnDocumentUri"));
  56. defaultFunctions.Add (FromName ("error", "FnError"));
  57. defaultFunctions.Add (FromName ("trace", "FnTrace"));
  58. defaultFunctions.Add (FromName ("abs", "FnAbs"));
  59. defaultFunctions.Add (FromName ("ceiling", "FnCeiling"));
  60. defaultFunctions.Add (FromName ("floor", "FnFloor"));
  61. defaultFunctions.Add (FromName ("round", "FnRound"));
  62. defaultFunctions.Add (FromName ("round-half-to-even", "FnRoundHalfToEven"));
  63. defaultFunctions.Add (FromName ("codepoints-to-string", "FnCodepointsToString"));
  64. defaultFunctions.Add (FromName ("string-to-codepoints", "FnStringToCodepoints"));
  65. defaultFunctions.Add (FromName ("compare", "FnCompare"));
  66. defaultFunctions.Add (FromName ("concat", "FnConcat"));
  67. defaultFunctions.Add (FromName ("string-join", "FnStringJoin"));
  68. defaultFunctions.Add (FromName ("substring", "FnSubstring"));
  69. defaultFunctions.Add (FromName ("string-length", "FnStringLength"));
  70. defaultFunctions.Add (FromName ("normaize-space", "FnNormalizeSpace"));
  71. defaultFunctions.Add (FromName ("normalize-unicode", "FnNormalizeUnicode"));
  72. defaultFunctions.Add (FromName ("uppercase", "FnUpperCase"));
  73. defaultFunctions.Add (FromName ("lowercase", "FnLowerCase"));
  74. defaultFunctions.Add (FromName ("translate", "FnTranslate"));
  75. defaultFunctions.Add (FromName ("escape-uri", "FnEscapeUri"));
  76. defaultFunctions.Add (FromName ("contains", "FnContains"));
  77. defaultFunctions.Add (FromName ("starts-with", "FnStartsWith"));
  78. defaultFunctions.Add (FromName ("ends-with", "FnEndsWith"));
  79. defaultFunctions.Add (FromName ("substring-before", "FnSubstringBefore"));
  80. defaultFunctions.Add (FromName ("substring-after", "FnSubstringAfter"));
  81. defaultFunctions.Add (FromName ("matches", "FnMatches"));
  82. defaultFunctions.Add (FromName ("replace", "FnReplace"));
  83. defaultFunctions.Add (FromName ("tokenize", "FnTokenize"));
  84. defaultFunctions.Add (FromName ("resolve-uri", "FnResolveUri"));
  85. defaultFunctions.Add (FromName ("true", "FnTrue"));
  86. defaultFunctions.Add (FromName ("false", "FnFalse"));
  87. defaultFunctions.Add (FromName ("not", "FnNot"));
  88. defaultFunctions.Add (FromName ("resolve-qname", "FnResolveQName"));
  89. defaultFunctions.Add (FromName ("expand-qname", "FnExpandQName"));
  90. defaultFunctions.Add (FromName ("namespace-uri-for-prefix", "FnNamespaceUriForPrefix"));
  91. defaultFunctions.Add (FromName ("in-scope-prefixes", "FnInScopePrefixes"));
  92. defaultFunctions.Add (FromName ("name", "FnName"));
  93. defaultFunctions.Add (FromName ("local-name", "FnLocalName"));
  94. defaultFunctions.Add (FromName ("namespace-uri", "FnNamespaceUri"));
  95. defaultFunctions.Add (FromName ("number", "FnNumber"));
  96. defaultFunctions.Add (FromName ("lang", "FnLang"));
  97. defaultFunctions.Add (FromName ("root", "FnRoot"));
  98. defaultFunctions.Add (FromName ("boolean", "FnBoolean"));
  99. defaultFunctions.Add (FromName ("indexof", "FnIndexOf"));
  100. defaultFunctions.Add (FromName ("empty", "FnEmpty"));
  101. defaultFunctions.Add (FromName ("exists", "FnExists"));
  102. defaultFunctions.Add (FromName ("distinct-values", "FnDistinctValues"));
  103. defaultFunctions.Add (FromName ("insert-before", "FnInsertBefore"));
  104. defaultFunctions.Add (FromName ("remove", "FnRemove"));
  105. defaultFunctions.Add (FromName ("reverse", "FnReverse"));
  106. defaultFunctions.Add (FromName ("subsequence", "FnSubsequence"));
  107. defaultFunctions.Add (FromName ("unordered", "FnUnordered"));
  108. defaultFunctions.Add (FromName ("zero-or-one", "FnZeroOrOne"));
  109. defaultFunctions.Add (FromName ("one-or-more", "FnOneOrMore"));
  110. defaultFunctions.Add (FromName ("exactly-one", "FnExactlyOne"));
  111. defaultFunctions.Add (FromName ("deep-equal", "FnDeepEqual"));
  112. defaultFunctions.Add (FromName ("count", "FnCount"));
  113. defaultFunctions.Add (FromName ("avg", "FnAvg"));
  114. defaultFunctions.Add (FromName ("max", "FnMax"));
  115. defaultFunctions.Add (FromName ("min", "FnMin"));
  116. defaultFunctions.Add (FromName ("sum", "FnSum"));
  117. defaultFunctions.Add (FromName ("id", "FnId"));
  118. defaultFunctions.Add (FromName ("idref", "FnIdRef"));
  119. defaultFunctions.Add (FromName ("doc", "FnDoc"));
  120. defaultFunctions.Add (FromName ("collection", "FnCollection"));
  121. defaultFunctions.Add (FromName ("position", "FnPosition"));
  122. defaultFunctions.Add (FromName ("last", "FnLast"));
  123. defaultFunctions.Add (FromName ("current-datetime", "FnCurrentDateTime"));
  124. defaultFunctions.Add (FromName ("current-date", "FnCurrentDate"));
  125. defaultFunctions.Add (FromName ("current-time", "FnCurrentTime"));
  126. defaultFunctions.Add (FromName ("default-collation", "FnDefaultCollation"));
  127. defaultFunctions.Add (FromName ("implicit-timezone", "FnImplicitTimeZone"));
  128. // defaultFunctions.Add (FromName ("years-from-duration", "FnYearsFromDuration"));
  129. /*
  130. fnAtomicConstructor,
  131. fnYearsFromDuration, fnMonthsFromDuration,
  132. fnDaysFromDuration, fnHoursFromDuration,
  133. fnMinutesFromDuration, fnSecondsFromDuration,
  134. fnYearFromDateTime, fnMonthFromDateTime,
  135. fnDayFromDateTime, fnHoursFromDateTime,
  136. fnMinutesFromDateTime, fnSecondsFromDateTime,
  137. fnTimeZoneFromDateTime, fnYearFromDate, fnMonthFromDate,
  138. fnDayFromDate, fnTimeZoneFromDate, fnHoursFromTime,
  139. fnMinutesFromTime, fnSecondsFromTime,
  140. fnTimeZoneFromTime, fnAdjustDateTimeToTimeZone,
  141. fnAdjustDateToTimeZone, fnAdjustTimeToTimeZone,
  142. fnSubtractDateTimesYieldingYearMonthDuration,
  143. fnSubtractDateTimesYieldingDayTimeDuration,
  144. fnSubtractDatesYieldingYearMonthDuration,
  145. fnSubtractDatesYieldingDayTimeDuration,
  146. fnSubtractTimes,
  147. */
  148. }
  149. private static XQueryCliFunction FromName (string xname, string cliname)
  150. {
  151. return XQueryCliFunction.CreateFromMethodInfo (
  152. new XmlQualifiedName (xname, XQueryFunction.Namespace),
  153. FindNamedMethods (typeof (XQueryFunctionCliImpl), cliname)
  154. );
  155. }
  156. internal static XQueryCliFunction FromQName (XmlQualifiedName qname)
  157. {
  158. return XQueryCliFunction.CreateFromMethodInfo (
  159. qname, FindNamedMethods (Type.GetType (qname.Namespace), qname.Name));
  160. }
  161. private static bool FilterImpl (MemberInfo m, object filterCriteria)
  162. {
  163. return m.Name == filterCriteria.ToString ();
  164. }
  165. private static MemberFilter memberFilter = new MemberFilter (FilterImpl);
  166. private static MethodInfo [] FindNamedMethods (Type type, string name)
  167. {
  168. ArrayList al = new ArrayList (
  169. type.FindMembers (
  170. MemberTypes.Method,
  171. BindingFlags.Default | BindingFlags.Public | BindingFlags.Static,
  172. // FIXME: wait for anonymous method support
  173. // delegate (MemberInfo m, object filterCriteria) {
  174. // return m.Name == filterCriteria.ToString ();
  175. // },
  176. memberFilter,
  177. name));
  178. return al.ToArray (typeof (MethodInfo)) as MethodInfo [];
  179. }
  180. internal static XQueryFunction FindKnownFunction (
  181. XmlQualifiedName name)
  182. {
  183. switch (name.Namespace) {
  184. case XQueryFunction.Namespace:
  185. return defaultFunctions [name];
  186. case XmlSchema.XdtNamespace:
  187. case XmlSchema.Namespace:
  188. XmlSchemaType type = XmlSchemaType.GetBuiltInSimpleType (name);
  189. if (type != null)
  190. return null; // FIXME: atomic constructor
  191. type = XmlSchemaType.GetBuiltInComplexType (name);
  192. if (type == null)
  193. return null; // FIXME: atomic constructor?
  194. return null;
  195. default:
  196. return null;
  197. }
  198. }
  199. // Constructor
  200. internal XQueryFunction (XmlQualifiedName name, XQueryFunctionArgument [] args, SequenceType returnType)
  201. {
  202. this.name = name;
  203. this.args = args;
  204. this.returnType = returnType;
  205. }
  206. // Fields
  207. XmlQualifiedName name;
  208. XQueryFunctionArgument [] args;
  209. SequenceType returnType;
  210. // Properties
  211. public XmlQualifiedName Name {
  212. get { return name; }
  213. }
  214. public abstract int MinArgs { get; }
  215. public abstract int MaxArgs { get; }
  216. public XQueryFunctionArgument [] Args {
  217. get { return args; }
  218. }
  219. public SequenceType ReturnType {
  220. get { return returnType; }
  221. }
  222. public abstract object Invoke (XPathSequence current, object [] args);
  223. public virtual XPathSequence Evaluate (XPathSequence iter, ExprSequence args)
  224. {
  225. object [] instParams = new object [args.Count];
  226. for (int i = 0; i < args.Count; i++) {
  227. XPathSequence val = args [i].Evaluate (iter);
  228. instParams [i] = Args [i].Type.ToRuntimeType (val);
  229. }
  230. object o = Invoke (iter, instParams);
  231. if (o == null)
  232. return new XPathEmptySequence (iter.Context);
  233. if (o is XPathSequence)
  234. return (XPathSequence) o;
  235. XPathItem item = o as XPathItem;
  236. if (item == null)
  237. item = new XPathAtomicValue (o, ReturnType.SchemaType);
  238. return new SingleItemIterator (item, iter.Context);
  239. }
  240. }
  241. public class XQueryFunctionArgument
  242. {
  243. public XQueryFunctionArgument (XmlQualifiedName name, SequenceType type)
  244. {
  245. this.name = name;
  246. this.type = type;
  247. }
  248. XmlQualifiedName name;
  249. SequenceType type;
  250. public XmlQualifiedName Name {
  251. get { return name; }
  252. }
  253. public SequenceType Type {
  254. get { return type; }
  255. }
  256. }
  257. public class XQueryUserFunction : XQueryFunction
  258. {
  259. ExprSequence expr;
  260. internal XQueryUserFunction (XmlQualifiedName name,
  261. XQueryFunctionArgument [] parameters,
  262. ExprSequence expr,
  263. SequenceType returnType)
  264. : base (name, parameters, returnType)
  265. {
  266. this.expr = expr;
  267. }
  268. public override int MinArgs {
  269. get { return Args.Length; }
  270. }
  271. public override int MaxArgs {
  272. get { return Args.Length; }
  273. }
  274. public override object Invoke (XPathSequence current, object [] args)
  275. {
  276. throw new SystemException ("XQuery internal error: should not happen.");
  277. }
  278. public override XPathSequence Evaluate (XPathSequence iter, ExprSequence args)
  279. {
  280. for (int i = 0; i < Args.Length; i++)
  281. iter.Context.PushVariable (Args [i].Name, args [i].Evaluate (iter));
  282. XPathSequence seq = new ExprSequenceIterator (iter, expr);
  283. for (int i = 0; i < Args.Length; i++)
  284. iter.Context.PopVariable ();
  285. return seq;
  286. }
  287. }
  288. }
  289. #endif