PageRenderTime 66ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/ClojureCLR/Clojure/Clojure/Lib/RT.cs

https://github.com/dsebban/clojure-contrib
C# | 1891 lines | 1473 code | 288 blank | 130 comment | 323 complexity | 3e6a34bf80936825e2401f31f1277a2a MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /**
  2. * Copyright (c) David Miller. All rights reserved.
  3. * The use and distribution terms for this software are covered by the
  4. * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
  5. * which can be found in the file epl-v10.html at the root of this distribution.
  6. * By using this software in any fashion, you are agreeing to be bound by
  7. * the terms of this license.
  8. * You must not remove this notice, or any other, from this software.
  9. **/
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Collections;
  15. using System.Reflection;
  16. using System.Text.RegularExpressions;
  17. using System.Threading;
  18. using System.IO;
  19. using System.Diagnostics;
  20. using System.Runtime.CompilerServices;
  21. using RTProperties = clojure.runtime.Properties;
  22. namespace clojure.lang
  23. {
  24. public static class RT_Bootstrap_Flag
  25. {
  26. public static bool _doRTBootstrap = true;
  27. }
  28. public static class RT
  29. {
  30. #region Default symbol-to-class map
  31. //simple-symbol->class
  32. internal static readonly IPersistentMap DEFAULT_IMPORTS = map(
  33. //classes
  34. Symbol.create("AccessViolationException"), typeof(AccessViolationException),
  35. Symbol.create("ActivationContext"), typeof(ActivationContext),
  36. Symbol.create("Activator"), typeof(Activator),
  37. Symbol.create("AppDomain"), typeof(AppDomain),
  38. Symbol.create("AppDomainManager"), typeof(AppDomainManager),
  39. Symbol.create("AppDomainSetup"), typeof(AppDomainSetup),
  40. Symbol.create("AppDomainUnloadedException"), typeof(AppDomainUnloadedException),
  41. Symbol.create("ApplicationException"), typeof(ApplicationException),
  42. Symbol.create("ApplicationId"), typeof(ApplicationId),
  43. Symbol.create("ApplicationIdentity"), typeof(ApplicationIdentity),
  44. Symbol.create("ArgumentException"), typeof(ArgumentException),
  45. Symbol.create("ArgumentNullException"), typeof(ArgumentNullException),
  46. Symbol.create("ArgumentOutOfRangeException"), typeof(ArgumentOutOfRangeException),
  47. Symbol.create("ArithmeticException"), typeof(ArithmeticException),
  48. Symbol.create("Array"), typeof(Array),
  49. Symbol.create("ArrayTypeMismatchException"), typeof(ArrayTypeMismatchException),
  50. Symbol.create("AssemblyLoadEventArgs"), typeof(AssemblyLoadEventArgs),
  51. Symbol.create("Attribute"), typeof(Attribute),
  52. Symbol.create("AttributeUsageAttribute"), typeof(AttributeUsageAttribute),
  53. Symbol.create("BadImageFormatException"), typeof(BadImageFormatException),
  54. Symbol.create("BitConverter"), typeof(BitConverter),
  55. Symbol.create("Buffer"), typeof(Buffer),
  56. Symbol.create("CannotUnloadAppDomainException"), typeof(CannotUnloadAppDomainException),
  57. Symbol.create("CharEnumerator"), typeof(CharEnumerator),
  58. Symbol.create("CLSCompliantAttribute"), typeof(CLSCompliantAttribute),
  59. Symbol.create("Console"), typeof(Console),
  60. Symbol.create("ConsoleCancelEventArgs"), typeof(ConsoleCancelEventArgs),
  61. Symbol.create("ContextBoundObject"), typeof(ContextBoundObject),
  62. //Symbol.create("ContextMarshalException"), typeof(ContextMarshalException), -- obsolete
  63. Symbol.create("ContextStaticAttribute"), typeof(ContextStaticAttribute),
  64. Symbol.create("Convert"), typeof(Convert),
  65. Symbol.create("DataMisalignedException"), typeof(DataMisalignedException),
  66. Symbol.create("DBNull"), typeof(DBNull),
  67. Symbol.create("Delegate"), typeof(Delegate),
  68. Symbol.create("DivideByZeroException"), typeof(DivideByZeroException),
  69. Symbol.create("DllNotFoundException"), typeof(DllNotFoundException),
  70. Symbol.create("DuplicateWaitObjectException"), typeof(DuplicateWaitObjectException),
  71. Symbol.create("EntryPointNotFoundException"), typeof(EntryPointNotFoundException),
  72. Symbol.create("Enum"), typeof(Enum),
  73. Symbol.create("Environment"), typeof(Environment),
  74. Symbol.create("EventArgs"), typeof(EventArgs),
  75. Symbol.create("Exception"), typeof(Exception),
  76. Symbol.create("ExecutionEngineException"), typeof(ExecutionEngineException),
  77. Symbol.create("FieldAccessException"), typeof(FieldAccessException),
  78. Symbol.create("FileStyleUriParser"), typeof(FileStyleUriParser),
  79. Symbol.create("FlagsAttribute"), typeof(FlagsAttribute),
  80. Symbol.create("FormatException"), typeof(FormatException),
  81. Symbol.create("FtpStyleUriParser"), typeof(FtpStyleUriParser),
  82. Symbol.create("GC"), typeof(GC),
  83. Symbol.create("GenericUriParser"), typeof(GenericUriParser),
  84. Symbol.create("GopherStyleUriParser"), typeof(GopherStyleUriParser),
  85. Symbol.create("HttpStyleUriParser"), typeof(HttpStyleUriParser),
  86. Symbol.create("IndexOutOfRangeException"), typeof(IndexOutOfRangeException),
  87. Symbol.create("InsufficientMemoryException"), typeof(InsufficientMemoryException),
  88. Symbol.create("InvalidCastException"), typeof(InvalidCastException),
  89. Symbol.create("InvalidOperationException"), typeof(InvalidOperationException),
  90. Symbol.create("InvalidProgramException"), typeof(InvalidProgramException),
  91. Symbol.create("InvalidTimeZoneException"), typeof(InvalidTimeZoneException),
  92. Symbol.create("LdapStyleUriParser"), typeof(LdapStyleUriParser),
  93. Symbol.create("LoaderOptimizationAttribute"), typeof(LoaderOptimizationAttribute),
  94. Symbol.create("LocalDataStoreSlot"), typeof(LocalDataStoreSlot),
  95. Symbol.create("MarshalByRefObject"), typeof(MarshalByRefObject),
  96. Symbol.create("Math"), typeof(Math),
  97. Symbol.create("MemberAccessException"), typeof(MemberAccessException),
  98. Symbol.create("MethodAccessException"), typeof(MethodAccessException),
  99. Symbol.create("MissingFieldException"), typeof(MissingFieldException),
  100. Symbol.create("MissingMemberException"), typeof(MissingMemberException),
  101. Symbol.create("MTAThreadAttribute"), typeof(MTAThreadAttribute),
  102. Symbol.create("MulticastDelegate"), typeof(MulticastDelegate),
  103. Symbol.create("MulticastNotSupportedException"), typeof(MulticastNotSupportedException),
  104. Symbol.create("NetPipeStyleUriParser"), typeof(NetPipeStyleUriParser),
  105. Symbol.create("NetTcpStyleUriParser"), typeof(NetTcpStyleUriParser),
  106. Symbol.create("NewsStyleUriParser"), typeof(NewsStyleUriParser),
  107. Symbol.create("NonSerializedAttribute"), typeof(NonSerializedAttribute),
  108. Symbol.create("NotFiniteNumberException"), typeof(NotFiniteNumberException),
  109. Symbol.create("NotImplementedException"), typeof(NotImplementedException),
  110. Symbol.create("NotSupportedException"), typeof(NotSupportedException),
  111. Symbol.create("Nullable"), typeof(Nullable),
  112. Symbol.create("NullReferenceException"), typeof(NullReferenceException),
  113. Symbol.create("Object"), typeof(Object),
  114. Symbol.create("ObjectDisposedException"), typeof(ObjectDisposedException),
  115. Symbol.create("ObsoleteAttribute"), typeof(ObsoleteAttribute),
  116. Symbol.create("OperatingSystem"), typeof(OperatingSystem),
  117. Symbol.create("OperationCanceledException"), typeof(OperationCanceledException),
  118. Symbol.create("OutOfMemoryException"), typeof(OutOfMemoryException),
  119. Symbol.create("OverflowException"), typeof(OverflowException),
  120. Symbol.create("ParamArrayAttribute"), typeof(ParamArrayAttribute),
  121. Symbol.create("PlatformNotSupportedException"), typeof(PlatformNotSupportedException),
  122. Symbol.create("Random"), typeof(Random),
  123. Symbol.create("RankException"), typeof(RankException),
  124. Symbol.create("ResolveEventArgs"), typeof(ResolveEventArgs),
  125. Symbol.create("SerializableAttribute"), typeof(SerializableAttribute),
  126. Symbol.create("StackOverflowException"), typeof(StackOverflowException),
  127. Symbol.create("STAThreadAttribute"), typeof(STAThreadAttribute),
  128. Symbol.create("String"), typeof(String),
  129. Symbol.create("StringComparer"), typeof(StringComparer),
  130. Symbol.create("SystemException"), typeof(SystemException),
  131. Symbol.create("ThreadStaticAttribute"), typeof(ThreadStaticAttribute),
  132. Symbol.create("TimeoutException"), typeof(TimeoutException),
  133. Symbol.create("TimeZone"), typeof(TimeZone),
  134. Symbol.create("TimeZoneInfo"), typeof(TimeZoneInfo),
  135. Symbol.create("TimeZoneNotFoundException"), typeof(TimeZoneNotFoundException),
  136. // Symbol.create("TimeZoneInfo.AdjustmentRule"),typeof(TimeZoneInfo.AdjustmentRule),
  137. Symbol.create("Type"), typeof(Type),
  138. Symbol.create("TypeInitializationException"), typeof(TypeInitializationException),
  139. Symbol.create("TypeLoadException"), typeof(TypeLoadException),
  140. Symbol.create("TypeUnloadedException"), typeof(TypeUnloadedException),
  141. Symbol.create("UnauthorizedAccessException"), typeof(UnauthorizedAccessException),
  142. Symbol.create("UnhandledExceptionEventArgs"), typeof(UnhandledExceptionEventArgs),
  143. Symbol.create("Uri"), typeof(Uri),
  144. Symbol.create("UriBuilder"), typeof(UriBuilder),
  145. Symbol.create("UriFormatException"), typeof(UriFormatException),
  146. Symbol.create("UriParser"), typeof(UriParser),
  147. // Symbol.create(""),typeof(UriTemplate),
  148. // Symbol.create(""),typeof(UriTemplateEquivalenceComparer),
  149. // Symbol.create(""),typeof(UriTemplateMatch),
  150. // Symbol.create(""),typeof(UriTemplateMatchException),
  151. // Symbol.create(""),typeof(UriTemplateTable),
  152. Symbol.create("UriTypeConverter"), typeof(UriTypeConverter),
  153. Symbol.create("ValueType"), typeof(ValueType),
  154. Symbol.create("Version"), typeof(Version),
  155. Symbol.create("WeakReference"), typeof(WeakReference),
  156. // structures/
  157. Symbol.create("ArgIterator"), typeof(ArgIterator),
  158. // Symbol.create(""),typeof(ArraySegment<T>),
  159. Symbol.create("Boolean"), typeof(Boolean),
  160. Symbol.create("Byte"), typeof(Byte),
  161. Symbol.create("Char"), typeof(Char),
  162. Symbol.create("ConsoleKeyInfo"), typeof(ConsoleKeyInfo),
  163. Symbol.create("DateTime"), typeof(DateTime),
  164. Symbol.create("DateTimeOffset"), typeof(DateTimeOffset),
  165. Symbol.create("Decimal"), typeof(Decimal),
  166. Symbol.create("Double"), typeof(Double),
  167. Symbol.create("Guid"), typeof(Guid),
  168. Symbol.create("Int16"), typeof(Int16),
  169. Symbol.create("Int32"), typeof(Int32),
  170. Symbol.create("Int64"), typeof(Int64),
  171. Symbol.create("IntPtr"), typeof(IntPtr),
  172. Symbol.create("ModuleHandle"), typeof(ModuleHandle),
  173. // Symbol.create(""),typeof(Nullable<T>),
  174. Symbol.create("RuntimeArgumentHandle"), typeof(RuntimeArgumentHandle),
  175. Symbol.create("RuntimeFieldHandle"), typeof(RuntimeFieldHandle),
  176. Symbol.create("RuntimeMethodHandle"), typeof(RuntimeMethodHandle),
  177. Symbol.create("RuntimeTypeHandle"), typeof(RuntimeTypeHandle),
  178. Symbol.create("SByte"), typeof(SByte),
  179. Symbol.create("Single"), typeof(Single),
  180. Symbol.create("TimeSpan"), typeof(TimeSpan),
  181. Symbol.create("TimeZoneInfo.TransitionTime"), typeof(TimeZoneInfo.TransitionTime),
  182. Symbol.create("TypedReference"), typeof(TypedReference),
  183. Symbol.create("UInt16"), typeof(UInt16),
  184. Symbol.create("UInt32"), typeof(UInt32),
  185. Symbol.create("UInt64"), typeof(UInt64),
  186. Symbol.create("UIntPtr"), typeof(UIntPtr),
  187. // Symbol.create(""),typeof(Void),
  188. // interfaces/
  189. Symbol.create("AppDomain"), typeof(AppDomain),
  190. Symbol.create("IAppDomainSetup"), typeof(IAppDomainSetup),
  191. Symbol.create("IAsyncResult"), typeof(IAsyncResult),
  192. Symbol.create("ICloneable"), typeof(ICloneable),
  193. Symbol.create("IComparable"), typeof(IComparable),
  194. //Symbol.create(""),typeof(IComparable<T>),
  195. Symbol.create("IConvertible"), typeof(IConvertible),
  196. Symbol.create("ICustomFormatter"), typeof(ICustomFormatter),
  197. Symbol.create("IDisposable"), typeof(IDisposable),
  198. //Symbol.create(""),typeof(IEquatable<T>),
  199. Symbol.create("IFormatProvider"), typeof(IFormatProvider),
  200. Symbol.create("IFormattable"), typeof(IFormattable),
  201. Symbol.create("IServiceProvider"), typeof(IServiceProvider),
  202. // delegates/
  203. Symbol.create("Action"), typeof(Action),
  204. // Symbol.create(""),typeof(Action<T>/
  205. // Symbol.create(""),typeof(Action<T1,T2>/
  206. // Symbol.create(""),typeof(Action<T1,T2,T3>/
  207. // Symbol.create(""),typeof(Action<T1,T2,T3,T4>/
  208. Symbol.create("AppDomainInitializer"), typeof(AppDomainInitializer),
  209. Symbol.create("AssemblyLoadEventHandler"), typeof(AssemblyLoadEventHandler),
  210. Symbol.create("AsyncCallback"), typeof(AsyncCallback),
  211. // Symbol.create(""),typeof(Comparison<T>),
  212. Symbol.create("ConsoleCancelEventHandler"), typeof(ConsoleCancelEventHandler),
  213. //Symbol.create(""),typeof(Converter<TInput,TOutput>),
  214. Symbol.create("CrossAppDomainDelegate"), typeof(CrossAppDomainDelegate),
  215. Symbol.create("EventHandler"), typeof(EventHandler),
  216. // Symbol.create(""),typeof(EventHandler<TEventArgs>),
  217. // Symbol.create(""),typeof(Func<TResult>),
  218. // Symbol.create(""),typeof(Func<T,TResult>/
  219. // Symbol.create(""),typeof(Func<T1, T2, TResult>/
  220. // Symbol.create(""),typeof(Func<T1, T2, T3, TResult>/
  221. // FSymbol.create(""),typeof(Func<T1, T2, T3, T4, TResult>/
  222. // Symbol.create(""),typeof(Predicate<T>),
  223. Symbol.create("ResolveEventHandler"), typeof(ResolveEventHandler),
  224. Symbol.create("UnhandledExceptionEventHandler"), typeof(UnhandledExceptionEventHandler),
  225. // Enumerations/
  226. Symbol.create("ActivationContext.ContextForm"), typeof(ActivationContext.ContextForm),
  227. Symbol.create("AppDomainManagerInitializationOptions"), typeof(AppDomainManagerInitializationOptions),
  228. Symbol.create("AttributeTargets"), typeof(AttributeTargets),
  229. Symbol.create("Base64FormattingOptions"), typeof(Base64FormattingOptions),
  230. Symbol.create("ConsoleColor"), typeof(ConsoleColor),
  231. Symbol.create("ConsoleKey"), typeof(ConsoleKey),
  232. Symbol.create("ConsoleModifiers"), typeof(ConsoleModifiers),
  233. Symbol.create("ConsoleSpecialKey"), typeof(ConsoleSpecialKey),
  234. Symbol.create("DateTimeKind"), typeof(DateTimeKind),
  235. Symbol.create("DayOfWeek"), typeof(DayOfWeek),
  236. Symbol.create("Environment.SpecialFolder"), typeof(Environment.SpecialFolder),
  237. Symbol.create("EnvironmentVariableTarget"), typeof(EnvironmentVariableTarget),
  238. Symbol.create("GCCollectionMode"), typeof(GCCollectionMode),
  239. Symbol.create("GenericUriParserOptions"), typeof(GenericUriParserOptions),
  240. Symbol.create("LoaderOptimization"), typeof(LoaderOptimization),
  241. Symbol.create("MidpointRounding"), typeof(MidpointRounding),
  242. Symbol.create("PlatformID"), typeof(PlatformID),
  243. Symbol.create("StringComparison"), typeof(StringComparison),
  244. Symbol.create("StringSplitOptions"), typeof(StringSplitOptions),
  245. Symbol.create("TypeCode"), typeof(TypeCode),
  246. Symbol.create("UriComponents"), typeof(UriComponents),
  247. Symbol.create("UriFormat"), typeof(UriFormat),
  248. Symbol.create("UriHostNameType"), typeof(UriHostNameType),
  249. Symbol.create("UriIdnScope"), typeof(UriIdnScope),
  250. Symbol.create("UriKind"), typeof(UriKind),
  251. Symbol.create("UriPartial"), typeof(UriPartial),
  252. // ADDED THESE TO SUPPORT THE BOOTSTRAPPING IN THE JAVA CORE.CLJ
  253. Symbol.create("StringBuilder"), typeof(StringBuilder),
  254. Symbol.create("BigInteger"), typeof(java.math.BigInteger),
  255. Symbol.create("BigDecimal"), typeof(java.math.BigDecimal),
  256. Symbol.create("Environment"), typeof(System.Environment)
  257. );
  258. #endregion
  259. #region Some misc. goodies
  260. public static readonly object[] EMPTY_OBJECT_ARRAY = new Object[] { };
  261. static RTProperties _versionProperties = new RTProperties();
  262. public static RTProperties GetVersionProperties() { return _versionProperties; }
  263. public const string CLOJURE_LOAD_PATH = "clojure.load.path";
  264. #endregion
  265. #region It's true (or not)
  266. // TODO: Should these really be object? In ClojureJVM, we would be trying to avoid boxing.
  267. public static readonly Boolean T = true;//Keyword.intern(Symbol.create(null, "t"));
  268. public static readonly Boolean F = false;//Keyword.intern(Symbol.create(null, "t"));
  269. public static bool IsTrue(object o)
  270. {
  271. if (o == null)
  272. return false;
  273. if (o is Boolean)
  274. return (Boolean)o;
  275. else
  276. return true;
  277. }
  278. #endregion
  279. #region Predefined namespaces
  280. // We need this initialization to happen earlier than most of the Var inits.
  281. public static readonly Namespace CLOJURE_NS
  282. = Namespace.findOrCreate(Symbol.create("clojure.core"));
  283. #endregion
  284. #region Useful Keywords
  285. public static readonly Keyword TAG_KEY
  286. = Keyword.intern(null, "tag");
  287. public static readonly Keyword LINE_KEY
  288. = Keyword.intern(null, "line");
  289. public static readonly Keyword FILE_KEY
  290. = Keyword.intern(null, "file");
  291. #endregion
  292. #region Vars (namespace-related)
  293. public static readonly Var CURRENT_NS
  294. = Var.intern(CLOJURE_NS, Symbol.create("*ns*"),CLOJURE_NS);
  295. public static readonly Var IN_NS_VAR
  296. = Var.intern(CLOJURE_NS, Symbol.create("in-ns"), F);
  297. public static readonly Var NS_VAR
  298. = Var.intern(CLOJURE_NS, Symbol.create("ns"), F);
  299. #endregion
  300. #region Vars (I/O-related)
  301. // TODO: These need to be tied into the DLR IO subsystem
  302. public static readonly Var OUT
  303. = Var.intern(CLOJURE_NS, Symbol.create("*out*"), System.Console.Out);
  304. public static readonly Var ERR
  305. = Var.intern(CLOJURE_NS, Symbol.create("*err*"), System.Console.Error);
  306. public static readonly Var IN =
  307. Var.intern(CLOJURE_NS, Symbol.create("*in*"),
  308. new clojure.lang.LineNumberingTextReader(System.Console.In));
  309. static readonly Var PRINT_READABLY
  310. = Var.intern(CLOJURE_NS, Symbol.create("*print-readably*"), T);
  311. public static readonly Var PRINT_META
  312. = Var.intern(CLOJURE_NS, Symbol.create("*print-meta*"), F);
  313. public static readonly Var PRINT_DUP
  314. = Var.intern(CLOJURE_NS, Symbol.create("*print-dup*"), F);
  315. static readonly Var FLUSH_ON_NEWLINE
  316. = Var.intern(CLOJURE_NS, Symbol.create("*flush-on-newline*"), T);
  317. static readonly Var PRINT_INITIALIZED
  318. = Var.intern(CLOJURE_NS, Symbol.create("print-initialized"));
  319. static readonly Var PR_ON
  320. = Var.intern(CLOJURE_NS, Symbol.create("pr-on"));
  321. public static readonly Var PRINT_LENGTH
  322. = Var.intern(CLOJURE_NS, Symbol.create("*print-length*"),null);
  323. public static readonly Var PRINT_LEVEL
  324. = Var.intern(CLOJURE_NS, Symbol.create("*print-length*"),null);
  325. #endregion
  326. #region Vars (miscellaneous)
  327. public static readonly Var ALLOW_UNRESOLVED_VARS
  328. = Var.intern(CLOJURE_NS, Symbol.create("*allow-unresolved-vars*"), F);
  329. public static readonly Var WARN_ON_REFLECTION
  330. = Var.intern(CLOJURE_NS, Symbol.create("*warn-on-reflection*"), T); // DEBUG_ONLY, should be F in production.
  331. public static readonly Var MACRO_META
  332. = Var.intern(CLOJURE_NS, Symbol.create("*macro-meta*"), null);
  333. public static readonly Var MATH_CONTEXT
  334. = Var.intern(CLOJURE_NS, Symbol.create("*math-context*"), null);
  335. public static readonly Var AGENT
  336. = Var.intern(CLOJURE_NS, Symbol.create("*agent*"), null);
  337. public static readonly Var READEVAL
  338. = Var.intern(CLOJURE_NS, Symbol.create("*read-eval*"), T);
  339. public static readonly Var CMD_LINE_ARGS
  340. = Var.intern(CLOJURE_NS, Symbol.create("*command-line-args*"), null);
  341. #endregion
  342. #region Clojure-environment IFns needing support
  343. static readonly Symbol IN_NAMESPACE = Symbol.create("in-ns");
  344. sealed class InNamespaceFn : AFn
  345. {
  346. public override object invoke(object arg1)
  347. {
  348. Symbol nsname = (Symbol)arg1;
  349. Namespace ns = Namespace.findOrCreate(nsname);
  350. CURRENT_NS.set(ns);
  351. return ns;
  352. }
  353. }
  354. static readonly Symbol NAMESPACE = Symbol.create("ns");
  355. static readonly Symbol IDENTICAL = Symbol.create("identical?");
  356. sealed class IdenticalFn : AFn
  357. {
  358. public override object invoke(object arg1, object arg2)
  359. {
  360. //return Object.ReferenceEquals(arg1, arg2) ? RT.T : RT.F;
  361. if ( arg1 is ValueType )
  362. return arg1.Equals(arg2) ? RT.T : RT.F;
  363. else
  364. return arg1 == arg2 ? RT.T : RT.F;
  365. }
  366. }
  367. static readonly Symbol LOAD_FILE = Symbol.create("load-file");
  368. sealed class LoadFileFn : AFn
  369. {
  370. public override object invoke(object arg1)
  371. {
  372. // TODO: Hook in loading here.
  373. return base.invoke(arg1);
  374. }
  375. }
  376. #endregion
  377. #region Initialization
  378. static RT()
  379. {
  380. _versionProperties.LoadFromString(clojure.lang.Properties.Resources.version);
  381. Keyword dockw = Keyword.intern(null, "doc");
  382. Keyword arglistskw = Keyword.intern(null, "arglists");
  383. Symbol namesym = Symbol.create("name");
  384. OUT.Tag = Symbol.create("System.IO.TextWriter");
  385. CURRENT_NS.Tag = Symbol.create("clojure.lang.Namespace");
  386. AGENT.setMeta(map(dockw, "The agent currently running an action on this thread, else nil."));
  387. AGENT.Tag = Symbol.create("clojure.lang.Agent");
  388. // We don't have MathContext (yet)
  389. //MATH_CONTEXT.Tag = Symbol.create("java.math.MathContext");
  390. // during bootstrap, ns same as in-ns
  391. Var nv = Var.intern(CLOJURE_NS, NAMESPACE, new InNamespaceFn());
  392. nv.setMacro();
  393. Var v;
  394. v = Var.intern(CLOJURE_NS, IN_NAMESPACE, new InNamespaceFn());
  395. v.setMeta(map(dockw, "Sets *ns* to the namespace named by the symbol, creating it if needed.",
  396. arglistskw, list(vector(namesym))));
  397. v = Var.intern(CLOJURE_NS, LOAD_FILE, new LoadFileFn());
  398. v.setMeta(map(dockw, "Sequentially read and evaluate the set of forms contained in the file.",
  399. arglistskw, list(vector(namesym))));
  400. v = Var.intern(CLOJURE_NS, IDENTICAL, new IdenticalFn());
  401. v.setMeta(map(dockw, "tests if 2 arguments are the same object",
  402. arglistskw, list(vector(Symbol.create("x"), Symbol.create("y")))));
  403. if ( RT_Bootstrap_Flag._doRTBootstrap )
  404. DoInit();
  405. }
  406. static void DoInit()
  407. {
  408. load("clojure/core");
  409. load("clojure/zip", false);
  410. //load("clojure/xml", false);
  411. load("clojure/set", false);
  412. PostBootstrapInit();
  413. }
  414. public static void PostBootstrapInit()
  415. {
  416. Var.pushThreadBindings(
  417. RT.map(CURRENT_NS, CURRENT_NS.deref(),
  418. WARN_ON_REFLECTION, WARN_ON_REFLECTION.deref()));
  419. try
  420. {
  421. Symbol USER = Symbol.create("user");
  422. Symbol CLOJURE = Symbol.create("clojure.core");
  423. Var in_ns = var("clojure.core", "in-ns");
  424. Var refer = var("clojure.core", "refer");
  425. in_ns.invoke(USER);
  426. refer.invoke(CLOJURE);
  427. MaybeLoadCljScript("user.clj");
  428. }
  429. finally
  430. {
  431. Var.popThreadBindings();
  432. }
  433. }
  434. #endregion
  435. #region Id generation
  436. // This is AtomicInteger in the JVM version.
  437. // The only place accessed is in nextID, so seems unnecessary.
  438. private static int _id;
  439. // initial-lowercase name, used in core.clj
  440. static public int nextID()
  441. {
  442. return Interlocked.Increment(ref _id);
  443. }
  444. #endregion
  445. #region Var support
  446. static public Var var(String ns, String name)
  447. {
  448. return Var.intern(Namespace.findOrCreate(Symbol.intern(null, ns)), Symbol.intern(null, name));
  449. }
  450. static public Var var(String ns, String name, Object init)
  451. {
  452. return Var.intern(Namespace.findOrCreate(Symbol.intern(null, ns)), Symbol.intern(null, name), init);
  453. }
  454. #endregion
  455. #region Collections support
  456. public static ISeq seq(object coll)
  457. {
  458. if (coll is ASeq)
  459. return (ASeq)coll;
  460. else if (coll is LazySeq)
  461. return ((LazySeq)coll).seq();
  462. else
  463. return seqFrom(coll);
  464. }
  465. private static ISeq seqFrom(object coll)
  466. {
  467. if (coll is Seqable)
  468. return ((Seqable)coll).seq();
  469. else if (coll == null)
  470. return null;
  471. else if (coll is IEnumerable) // java: Iterable
  472. return EnumeratorSeq.create(((IEnumerable)coll).GetEnumerator()); // IteratorSeq
  473. else if (coll.GetType().IsArray)
  474. return ArraySeq.createFromObject(coll);
  475. else if (coll is string)
  476. return StringSeq.create((string)coll);
  477. // The equivalent for Java:Map is IDictionary. IDictionary is IEnumerable, so is handled above.
  478. //else if(coll isntanceof Map)
  479. // return seq(((Map) coll).entrySet());
  480. // Used to be in the java version:
  481. //else if (coll is IEnumerator) // java: Iterator
  482. // return EnumeratorSeq.create((IEnumerator)coll);
  483. else
  484. throw new ArgumentException("Don't know how to create ISeq from: " + coll.GetType().Name);
  485. }
  486. static public Stream stream(object coll) {
  487. if (coll == null)
  488. return new Stream(EMPTY_GEN);
  489. else if (coll is Streamable)
  490. return ((Streamable)coll).stream();
  491. else if (coll is Fn) // TODO: Note use of Fn to imply castable to IFn. Should we do this? Why not just check for IFn?
  492. return new Stream((IFn)coll);
  493. else if (coll is IEnumerable) // java: Iterable
  494. return new Stream(new IteratorStream(((IEnumerable)coll).GetEnumerator())); // java: IteratorStream
  495. else if (coll.GetType().IsArray)
  496. return ArrayStream.createFromObject(coll);
  497. else if (coll is String)
  498. return ArrayStream.createFromObject(((String)coll).ToCharArray());
  499. else
  500. return new Stream(new ASeq.Src(RT.seq(coll)));
  501. }
  502. public static ISeq keys(object coll)
  503. {
  504. return APersistentMap.KeySeq.create(seq(coll));
  505. }
  506. public static ISeq vals(object coll)
  507. {
  508. return APersistentMap.ValSeq.create(seq(coll));
  509. }
  510. public static IPersistentMap meta(object x)
  511. {
  512. return x is IMeta
  513. ? ((IMeta)x).meta()
  514. : null;
  515. }
  516. public static int count(object o)
  517. {
  518. if (o == null)
  519. return 0;
  520. else if (o is Counted)
  521. return ((Counted)o).count();
  522. else if (o is IPersistentCollection)
  523. {
  524. ISeq s = seq(o);
  525. o = null;
  526. int i = 0;
  527. for (; s != null; s = s.next())
  528. {
  529. if (s is Counted)
  530. return i + s.count();
  531. i++;
  532. }
  533. return i;
  534. }
  535. else if (o is String)
  536. return ((String)o).Length;
  537. else if (o is ICollection)
  538. return ((ICollection)o).Count;
  539. else if (o is IDictionary)
  540. return ((IDictionary)o).Count;
  541. else if (o is Array)
  542. return ((Array)o).GetLength(0);
  543. throw new InvalidOperationException("count not supported on this type: " + o.GetType().Name);
  544. }
  545. public static IPersistentCollection conj(IPersistentCollection coll, Object x)
  546. {
  547. if (coll == null)
  548. return new PersistentList(x);
  549. return coll.cons(x);
  550. }
  551. public static ISeq cons(object x, object coll)
  552. {
  553. //ISeq y = seq(coll);
  554. if (coll == null)
  555. return new PersistentList(x);
  556. else if (coll is ISeq)
  557. return new Cons(x, (ISeq)coll);
  558. else
  559. return new Cons(x, seq(coll));
  560. }
  561. public static object first(object x)
  562. {
  563. if (x is ISeq)
  564. return ((ISeq)x).first();
  565. ISeq seq = RT.seq(x);
  566. return (seq == null)
  567. ? null
  568. : seq.first();
  569. }
  570. public static object second(object x)
  571. {
  572. return first(next(x));
  573. }
  574. public static object third(object x)
  575. {
  576. return first(next(next(x)));
  577. }
  578. public static object fourth(object x)
  579. {
  580. return first(next(next(next(x))));
  581. }
  582. public static ISeq next(object x)
  583. {
  584. if (x is ISeq)
  585. return ((ISeq)x).next();
  586. ISeq seq = RT.seq(x);
  587. if (seq == null)
  588. return null;
  589. return seq.next();
  590. }
  591. public static ISeq more(object x)
  592. {
  593. if (x is ISeq)
  594. return ((ISeq)x).more();
  595. ISeq seq = RT.seq(x);
  596. if (seq == null)
  597. return PersistentList.EMPTY;
  598. return seq.more();
  599. }
  600. public static object peek(object x)
  601. {
  602. return x == null
  603. ? null
  604. : ((IPersistentStack)x).peek();
  605. }
  606. public static object pop(object x)
  607. {
  608. return x == null
  609. ? null
  610. : ((IPersistentStack)x).pop();
  611. }
  612. static public Object get(Object coll, Object key)
  613. {
  614. if (coll == null)
  615. return null;
  616. else if (coll is Associative)
  617. return ((Associative)coll).valAt(key);
  618. else if (coll is IDictionary)
  619. {
  620. IDictionary m = (IDictionary)coll;
  621. return m[key];
  622. }
  623. else if (coll is IPersistentSet)
  624. {
  625. IPersistentSet set = (IPersistentSet)coll;
  626. return set.get(key);
  627. }
  628. else if (Util.IsNumeric(key) && (coll is string || coll.GetType().IsArray))
  629. {
  630. int n = Util.ConvertToInt(key);
  631. return n >= 0 && n < count(coll) ? nth(coll, n) : null;
  632. }
  633. return null;
  634. }
  635. static public Object get(Object coll, Object key, Object notFound)
  636. {
  637. if (coll == null)
  638. return notFound;
  639. else if (coll is Associative)
  640. return ((Associative)coll).valAt(key, notFound);
  641. else if (coll is IDictionary)
  642. {
  643. IDictionary m = (IDictionary)coll;
  644. if (m.Contains(key))
  645. return m[key];
  646. return notFound;
  647. }
  648. else if (coll is IPersistentSet)
  649. {
  650. IPersistentSet set = (IPersistentSet)coll;
  651. if (set.contains(key))
  652. return set.get(key);
  653. return notFound;
  654. }
  655. else if (Util.IsNumeric(key) && (coll is string || coll.GetType().IsArray))
  656. {
  657. int n = Util.ConvertToInt(key);
  658. return n >= 0 && n < count(coll) ? nth(coll, n) : notFound;
  659. }
  660. return notFound;
  661. }
  662. public static Associative assoc(object coll, object key, Object val)
  663. {
  664. if (coll == null)
  665. return new PersistentArrayMap(new object[] { key, val });
  666. return ((Associative)coll).assoc(key, val);
  667. }
  668. public static object contains(object coll, object key)
  669. {
  670. if (coll == null)
  671. return F;
  672. else if (coll is Associative)
  673. return ((Associative)coll).containsKey(key) ? T : F;
  674. else if (coll is IPersistentSet)
  675. return ((IPersistentSet)coll).contains(key) ? T : F;
  676. else if (coll is IDictionary)
  677. {
  678. IDictionary m = (IDictionary)coll;
  679. return m.Contains(key) ? T : F;
  680. }
  681. else if (Util.IsNumeric(key) && (coll is String || coll.GetType().IsArray))
  682. {
  683. int n = Util.ConvertToInt(key);
  684. return n >= 0 && n < count(coll);
  685. }
  686. return F;
  687. }
  688. public static object find(object coll, object key)
  689. {
  690. if (coll == null)
  691. return null;
  692. else if (coll is Associative)
  693. return ((Associative)coll).entryAt(key);
  694. else
  695. {
  696. IDictionary m = (IDictionary)coll;
  697. if (m.Contains(key))
  698. return new MapEntry(key, m[key]);
  699. return null;
  700. }
  701. }
  702. public static object dissoc(object coll, object key)
  703. {
  704. return coll == null
  705. ? null
  706. : ((IPersistentMap)coll).without(key);
  707. }
  708. static public Object nth(Object coll, int n)
  709. {
  710. if (coll == null)
  711. return null;
  712. else if (coll is IPersistentVector)
  713. return ((IPersistentVector)coll).nth(n);
  714. else if (coll is String)
  715. return ((string)coll)[n];
  716. else if (coll.GetType().IsArray)
  717. return ((Array)coll).GetValue(n); // TODO: Java has Reflector.prepRet -- check all uses.
  718. // Java has RandomAccess here. CLR has no equiv.
  719. else if (coll is IList) // Caused some infinite loops in places ASeq[].
  720. return ((IList)coll)[n];
  721. else if (coll is Match)
  722. return ((Match)coll).Groups[n];
  723. else if (coll is DictionaryEntry)
  724. {
  725. DictionaryEntry e = (DictionaryEntry)coll;
  726. if (n == 0)
  727. return e.Key;
  728. else if (n == 1)
  729. return e.Value;
  730. throw new IndexOutOfRangeException();
  731. }
  732. else if (coll.GetType().IsGenericType && coll.GetType().Name == "KeyValuePair`2")
  733. {
  734. if (n == 0)
  735. return coll.GetType().InvokeMember("Key", BindingFlags.GetProperty, null, coll, null);
  736. else if (n == 1)
  737. return coll.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, coll, null);
  738. throw new IndexOutOfRangeException();
  739. }
  740. else if (coll is IMapEntry)
  741. {
  742. IMapEntry e = (IMapEntry)coll;
  743. if (n == 0)
  744. return e.key();
  745. else if (n == 1)
  746. return e.val();
  747. throw new IndexOutOfRangeException();
  748. }
  749. else if (coll is Sequential)
  750. {
  751. ISeq seq = RT.seq(coll);
  752. coll = null;
  753. for (int i = 0; i <= n && seq != null; ++i, seq = seq.next())
  754. {
  755. if (i == n)
  756. return seq.first();
  757. }
  758. throw new IndexOutOfRangeException();
  759. }
  760. else
  761. throw new InvalidOperationException("nth not supported on this type: " + coll.GetType().Name);
  762. }
  763. static public Object nth(Object coll, int n, Object notFound)
  764. {
  765. if (coll == null)
  766. return notFound;
  767. else if (n < 0)
  768. return notFound;
  769. else if (coll is IPersistentVector)
  770. {
  771. IPersistentVector v = (IPersistentVector)coll;
  772. if (n < v.count())
  773. return v.nth(n);
  774. return notFound;
  775. }
  776. else if (coll is String)
  777. {
  778. String s = (String)coll;
  779. if (n < s.Length)
  780. return s[n];
  781. return notFound;
  782. }
  783. else if (coll.GetType().IsArray)
  784. {
  785. Array a = (Array)coll;
  786. if (n < a.Length)
  787. return a.GetValue(n); // Java: has call to Reflector.prepRet wrapped here.
  788. return notFound;
  789. }
  790. else if (coll is IList) // Changed to RandomAccess in Java Rev 1218.
  791. {
  792. IList list = (IList)coll;
  793. if (n < list.Count)
  794. return list[n];
  795. return notFound;
  796. }
  797. else if (coll is Match)
  798. {
  799. Match m = (Match)coll;
  800. if (n < m.Groups.Count)
  801. return m.Groups[n];
  802. return notFound;
  803. }
  804. else if (coll is DictionaryEntry)
  805. {
  806. DictionaryEntry e = (DictionaryEntry)coll;
  807. if (n == 0)
  808. return e.Key;
  809. else if (n == 1)
  810. return e.Value;
  811. return notFound;
  812. }
  813. else if (coll.GetType().IsGenericType && coll.GetType().Name == "KeyValuePair`2")
  814. {
  815. if (n == 0)
  816. return coll.GetType().InvokeMember("Key", BindingFlags.GetProperty, null, coll, null);
  817. else if (n == 1)
  818. return coll.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, coll, null);
  819. return notFound;
  820. }
  821. else if (coll is IMapEntry)
  822. {
  823. IMapEntry e = (IMapEntry)coll;
  824. if (n == 0)
  825. return e.key();
  826. else if (n == 1)
  827. return e.val();
  828. return notFound;
  829. }
  830. else if (coll is Sequential)
  831. {
  832. ISeq seq = RT.seq(coll);
  833. coll = null; // release in case GC
  834. for (int i = 0; i <= n && seq != null; ++i, seq = seq.next())
  835. {
  836. if (i == n)
  837. return seq.first();
  838. }
  839. return notFound;
  840. }
  841. else
  842. throw new InvalidOperationException("nth not supported on this type: " + coll.GetType().Name);
  843. }
  844. #endregion
  845. #region boxing/casts
  846. public static char charCast(object x)
  847. {
  848. return Convert.ToChar(x);
  849. }
  850. static public bool booleanCast(object x)
  851. {
  852. if (x is Boolean)
  853. return ((Boolean)x);
  854. return x != null;
  855. }
  856. public static byte byteCast(object x)
  857. {
  858. return (byte)Convert.ToDouble(x);
  859. }
  860. public static short shortCast(object x)
  861. {
  862. return (short)Convert.ToDouble(x);
  863. }
  864. public static int intCast(object x)
  865. {
  866. // ToInt32 rounds. We need truncation.
  867. return (int)Convert.ToDouble(x);
  868. }
  869. static public int intCast(char x)
  870. {
  871. return x;
  872. }
  873. static public int intCast(byte x)
  874. {
  875. return x;
  876. }
  877. static public int intCast(short x)
  878. {
  879. return x;
  880. }
  881. static public int intCast(int x)
  882. {
  883. return x;
  884. }
  885. static public int intCast(float x)
  886. {
  887. return (int)x;
  888. }
  889. static public int intCast(long x)
  890. {
  891. return (int)x;
  892. }
  893. static public int intCast(double x)
  894. {
  895. return (int)x;
  896. }
  897. public static long longCast(object x)
  898. {
  899. return (long)Convert.ToDouble(x);
  900. }
  901. public static long longCast(int x)
  902. {
  903. return x;
  904. }
  905. static public long longCast(float x)
  906. {
  907. return (long)x;
  908. }
  909. static public long longCast(long x)
  910. {
  911. return x;
  912. }
  913. static public long longCast(double x)
  914. {
  915. return (long)x;
  916. }
  917. public static float floatCast(object x)
  918. {
  919. return Convert.ToSingle(x);
  920. }
  921. public static float floatCast(int x)
  922. {
  923. return x;
  924. }
  925. public static float floatCast(float x)
  926. {
  927. return x;
  928. }
  929. public static float floatCast(long x)
  930. {
  931. return x;
  932. }
  933. public static float floatCast(double x)
  934. {
  935. return (float)x;
  936. }
  937. public static double doubleCast(object x)
  938. {
  939. return Convert.ToDouble(x);
  940. }
  941. public static double doubleCast(int x)
  942. {
  943. return x;
  944. }
  945. public static double doubleCast(float x)
  946. {
  947. return x;
  948. }
  949. public static double doubleCast(long x)
  950. {
  951. return x;
  952. }
  953. public static double doubleCast(double x)
  954. {
  955. return x;
  956. }
  957. #endregion
  958. #region More collection support
  959. public static IPersistentMap map(params object[] init)
  960. {
  961. return (init == null)
  962. ? PersistentArrayMap.EMPTY
  963. : (init.Length <= PersistentArrayMap.HASHTABLE_THRESHOLD)
  964. ? (IPersistentMap)new PersistentArrayMap(init)
  965. : (IPersistentMap)PersistentHashMap.create(init);
  966. }
  967. public static IPersistentSet set(params object[] init)
  968. {
  969. return PersistentHashSet.create1(init);
  970. }
  971. public static IPersistentVector vector(params object[] init)
  972. {
  973. return LazilyPersistentVector.createOwning(init);
  974. }
  975. public static IPersistentVector subvec(IPersistentVector v, int start, int end)
  976. {
  977. if (end < start || start < 0 || end > v.count())
  978. throw new IndexOutOfRangeException();
  979. if (start == end)
  980. return PersistentVector.EMPTY;
  981. return new APersistentVector.SubVector(null, v, start, end);
  982. }
  983. #endregion
  984. #region List support
  985. public static ISeq list()
  986. {
  987. return null;
  988. }
  989. public static ISeq list(object arg1)
  990. {
  991. return new PersistentList(arg1);
  992. }
  993. public static ISeq list(object arg1, object arg2)
  994. {
  995. return listStar(arg1, arg2, null);
  996. }
  997. public static ISeq list(object arg1, object arg2, object arg3)
  998. {
  999. return listStar(arg1, arg2, arg3, null);
  1000. }
  1001. public static ISeq list(object arg1, object arg2, object arg3, object arg4)
  1002. {
  1003. return listStar(arg1, arg2, arg3, arg4, null);
  1004. }
  1005. public static ISeq list(object arg1, object arg2, object arg3, object arg4, object arg5)
  1006. {
  1007. return listStar(arg1, arg2, arg3, arg4, arg5, null);
  1008. }
  1009. public static ISeq listStar(object arg1, ISeq rest)
  1010. {
  1011. return cons(arg1, rest);
  1012. }
  1013. public static ISeq listStar(object arg1, object arg2, ISeq rest)
  1014. {
  1015. return cons(arg1, cons(arg2, rest));
  1016. }
  1017. public static ISeq listStar(object arg1, object arg2, object arg3, ISeq rest)
  1018. {
  1019. return cons(arg1, cons(arg2, cons(arg3, rest)));
  1020. }
  1021. public static ISeq listStar(object arg1, object arg2, object arg3, object arg4, ISeq rest)
  1022. {
  1023. return cons(arg1, cons(arg2, cons(arg3, cons(arg4, rest))));
  1024. }
  1025. public static ISeq listStar(object arg1, object arg2, object arg3, object arg4, object arg5, ISeq rest)
  1026. {
  1027. return cons(arg1, cons(arg2, cons(arg3, cons(arg4, cons(arg5, rest)))));
  1028. }
  1029. public static ISeq arrayToList(object[] items)
  1030. {
  1031. ISeq ret = null;
  1032. for (int i = items.Length - 1; i >= 0; --i)
  1033. ret = (ISeq)cons(items[i], ret);
  1034. return ret;
  1035. }
  1036. public static object[] toArray(object coll)
  1037. {
  1038. if (coll == null)
  1039. return EMPTY_OBJECT_ARRAY;
  1040. else if (coll is object[])
  1041. return (object[])coll;
  1042. // In CLR, ICollection does not have a toArray.
  1043. // ICollection derives from IEnumerable, so the IEnumerable clause will take care of it.
  1044. //if (coll instanceof Collection)
  1045. // return ((Collection)coll).toArray();
  1046. // TODO: List has a toArray -- generic -- need type.
  1047. else if (coll is IEnumerable)
  1048. return IEnumToArray((IEnumerable)coll);
  1049. // Java has Map here, but IDictionary is IEnumerable, so it will be handled by previous clause.
  1050. else if (coll is String)
  1051. {
  1052. char[] chars = ((String)coll).ToCharArray();
  1053. // TODO: Determine if we need to make a copy (Java version does, not sure if CLR requires it)
  1054. object[] ret = new object[chars.Length];
  1055. for (int i = 0; i < chars.Length; i++)
  1056. ret[i] = chars[i];
  1057. return ret;
  1058. }
  1059. // This used to be in the java version. No longer. Do we need?
  1060. //else if (coll is ISeq)
  1061. // return toArray((ISeq)coll);
  1062. //else if (coll is IPersistentCollection)
  1063. // return toArray(((IPersistentCollection)coll).seq());
  1064. else if (coll.GetType().IsArray)
  1065. {
  1066. ISeq s = (seq(coll));
  1067. object[] ret = new object[count(s)];
  1068. for (int i = 0; i < ret.Length; i++, s = s.next())
  1069. ret[i] = s.first();
  1070. return ret;
  1071. }
  1072. else
  1073. throw new Exception("Unable to convert: " + coll.GetType() + " to Object[]");
  1074. }
  1075. private static object[] IEnumToArray(IEnumerable e)
  1076. {
  1077. List<object> list = new List<object>();
  1078. foreach (object o in e)
  1079. list.Add(o);
  1080. return list.ToArray();
  1081. }
  1082. //private static object[] toArray(ISeq seq)
  1083. //{
  1084. // object[] array = new object[seq.count…

Large files files are truncated, but you can click here to view the full file