/interpreter/tags/at2dist220411/src/edu/vub/at/objects/natives/NATNamespace.java

http://ambienttalk.googlecode.com/ · Java · 238 lines · 125 code · 22 blank · 91 comment · 8 complexity · 850ef410875b9c40919f8aadeaa3606c MD5 · raw file

  1. /**
  2. * AmbientTalk/2 Project
  3. * NATNamespace.java created on 6-sep-2006 at 14:33:41
  4. * (c) Programming Technology Lab, 2006 - 2007
  5. * Authors: Tom Van Cutsem & Stijn Mostinckx
  6. *
  7. * Permission is hereby granted, free of charge, to any person
  8. * obtaining a copy of this software and associated documentation
  9. * files (the "Software"), to deal in the Software without
  10. * restriction, including without limitation the rights to use,
  11. * copy, modify, merge, publish, distribute, sublicense, and/or
  12. * sell copies of the Software, and to permit persons to whom the
  13. * Software is furnished to do so, subject to the following
  14. * conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be
  17. * included in all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  21. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  23. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  24. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  25. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  26. * OTHER DEALINGS IN THE SOFTWARE.
  27. */
  28. package edu.vub.at.objects.natives;
  29. import edu.vub.at.eval.Evaluator;
  30. import edu.vub.at.exceptions.InterpreterException;
  31. import edu.vub.at.exceptions.XDuplicateSlot;
  32. import edu.vub.at.exceptions.XIOProblem;
  33. import edu.vub.at.exceptions.XTypeMismatch;
  34. import edu.vub.at.objects.ATAbstractGrammar;
  35. import edu.vub.at.objects.ATClosure;
  36. import edu.vub.at.objects.ATObject;
  37. import edu.vub.at.objects.ATTable;
  38. import edu.vub.at.objects.ATTypeTag;
  39. import edu.vub.at.objects.coercion.NativeTypeTags;
  40. import edu.vub.at.objects.grammar.ATSymbol;
  41. import edu.vub.at.objects.mirrors.NativeClosure;
  42. import edu.vub.at.objects.mirrors.Reflection;
  43. import edu.vub.at.parser.NATParser;
  44. import edu.vub.util.TempFieldGenerator;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.util.LinkedList;
  48. import java.util.Set;
  49. import java.util.Vector;
  50. /**
  51. * Instances of the class NATNamespace represent namespace objects.
  52. *
  53. * Namespace objects act as regular AmbientTalk objects with the following differences and conventions:
  54. * - Behaviourally, a namespace object is mirrored by a mirror whose doesNotUnderstand
  55. * method reacts differently from the standard semantics of raising a 'selector not found' exception.
  56. * - Structurally, a namespace has the lexical root as its lexical parent and the dynamic root as its dynamic parent.
  57. * Furthermore, a namespace object encapsulates an absolute file system path and a relative 'path name'.
  58. * The name should correspond to a portion of the tail of the absolute path.
  59. * These variables are not visible to AmbientTalk code.
  60. *
  61. * When a slot is looked up in a namespace NS for a path P (via meta_select) and not found, the namespace object
  62. * queries the local file system to see whether the selector corresponds to a directory or file in the
  63. * directory P. Either the selector:
  64. * - corresponds to a directory, in which case the missing slot is bound to a new namespace object corresponding to the path P/selector
  65. * - corresponds to a file named selector.at, in which case:
  66. * 1) the slot is temporarily bound to nil
  67. * (this is to prevent loops when the code to be evaluated would refer to itself;
  68. * it also means there can be no circular dependencies, because referring to a slot still under construction yields nil)
  69. * 2) a new object FS (the 'file scope') is created.
  70. * This object acts as the local scope for the file and has access to its 'enclosing' namespace via the '~' slot.
  71. * Hence, it can refer to other files in the 'current directory' using ~.filename
  72. * 3) the code in the file is loaded and evaluated in the context (current=FS, self=FS, super=FS.parent=dynroot)
  73. * 4) the result of the evaluated code is bound to the missing slot.
  74. * The next time the slot is queried for in the namespace, the value is immediately returned. This prevents
  75. * files from being loaded twice.
  76. * - does not correspond to any file or directory, resulting in a selector not found exception as usual.
  77. *
  78. * @author tvcutsem
  79. * @author smostinc
  80. */
  81. public final class NATNamespace extends NATObject {
  82. private static final String _AT_EXT_ = ".at";
  83. private final File path_;
  84. private final String name_;
  85. /**
  86. * A namespace object encapsulates a given absolute path and represents the given relative path.
  87. *
  88. * @param name the name of this namespace (corresponding to a certain depth to the tail of the absolute path)
  89. * @param path an absolute path referring to a local file system directory.
  90. */
  91. public NATNamespace(String name, File path) {
  92. super();
  93. name_ = name;
  94. path_ = path;
  95. }
  96. /**
  97. * Private constructor used only for cloning
  98. */
  99. private NATNamespace(FieldMap map,
  100. Vector state,
  101. LinkedList customFields,
  102. MethodDictionary methodDict,
  103. ATObject dynamicParent,
  104. ATObject lexicalParent,
  105. byte flags,
  106. ATTypeTag[] types,
  107. File path,
  108. String name,
  109. Set freeVars) throws InterpreterException {
  110. super(map, state, customFields, methodDict, dynamicParent, lexicalParent, flags, types, freeVars);
  111. path_ = path;
  112. name_ = name;
  113. }
  114. /**
  115. * For a namespace object, doesNotUnderstand triggers the querying of the local file system
  116. * to load files corresponding to the missing selector.
  117. */
  118. public ATClosure meta_doesNotUnderstand(ATSymbol selector) throws InterpreterException {
  119. // first, convert the AmbientTalk name to a Java selector. Java selectors are always valid filenames because
  120. // they do not contain special operator characters
  121. String javaSelector = Reflection.upSelector(selector);
  122. // first, try to see if the file exists and corresponds to a directory
  123. File dir = new File(path_, javaSelector);
  124. if (dir.exists() && dir.isDirectory()) {
  125. // create a new namespace object for this directory
  126. final NATNamespace childNS = new NATNamespace(name_ + File.separator + javaSelector, dir);
  127. // bind the new child namespace to the selector
  128. this.meta_defineField(selector, childNS);
  129. return new NativeClosure(this) {
  130. public ATObject base_apply(ATTable args) {
  131. return childNS;
  132. }
  133. };
  134. } else {
  135. // try to see if a file with extension .at exists corresponding to the selector
  136. File src = new File(path_, javaSelector + _AT_EXT_);
  137. if (src.exists() && src.isFile()) {
  138. // bind the missing slot to nil to prevent calling this dNU recursively when evaluating the code in the file
  139. this.meta_defineField(selector, Evaluator.getNil());
  140. // create a new file scope object for this file
  141. NATObject fileScope = createFileScopeFor(this);
  142. try {
  143. // load the code from the file
  144. String code = Evaluator.loadContentOfFile(src);
  145. // construct the proper evaluation context for the code
  146. NATContext ctx = new NATContext(fileScope, fileScope);
  147. // parse and evaluate the code in the proper context and bind its result to the missing slot
  148. ATAbstractGrammar source = NATParser.parse(src.getAbsolutePath(), code);
  149. final ATObject result = source.meta_eval(ctx);
  150. this.impl_invokeMutator(this, selector.asAssignmentSymbol(), NATTable.of(result));
  151. //this.meta_assignField(this, selector, result);
  152. // keeping up with the UAP: if the return value of a module is
  153. // a function, the function itself is returned (and most presumably
  154. // applied immediately). This allows modules to be parameterized easily.
  155. if (result.meta_isTaggedAs(NativeTypeTags._CLOSURE_).asNativeBoolean().javaValue) {
  156. return result.asClosure();
  157. } else {
  158. return new NativeClosure(this) {
  159. public ATObject base_apply(ATTable args) {
  160. return result;
  161. }
  162. };
  163. }
  164. } catch (IOException e) {
  165. throw new XIOProblem(e);
  166. }
  167. } else { // neither a matching directory nor a matching file.at were found
  168. // perform the default dNU behaviour, which means raising a 'selector not found' exception
  169. return super.meta_doesNotUnderstand(selector);
  170. }
  171. }
  172. }
  173. public NATText meta_print() throws InterpreterException {
  174. return NATText.atValue("<ns:"+name_+">");
  175. }
  176. public NATText impl_asCode(TempFieldGenerator objectMap) {
  177. return NATText.atValue("/" + name_.replace('/', '.'));
  178. }
  179. public static NATObject createFileScopeFor(NATNamespace ns) {
  180. NATObject fileScope = new NATObject();
  181. // a fileScope object is empty, save for a reference to its creating namespace
  182. try {
  183. fileScope.meta_defineField(Evaluator._CURNS_SYM_, ns);
  184. } catch (XDuplicateSlot e) {
  185. // impossible: the object is empty
  186. e.printStackTrace();
  187. } catch (XTypeMismatch e) {
  188. // impossible: the given selector is native
  189. e.printStackTrace();
  190. } catch (InterpreterException e) {
  191. // impossible : call cannot be intercepted : namespaces are not mirages
  192. e.printStackTrace();
  193. }
  194. return fileScope;
  195. }
  196. protected NATObject createClone(FieldMap map,
  197. Vector state,
  198. LinkedList customFields,
  199. MethodDictionary methodDict,
  200. ATObject dynamicParent,
  201. ATObject lexicalParent,
  202. byte flags, ATTypeTag[] types,
  203. Set freeVars) throws InterpreterException {
  204. return new NATNamespace(map,
  205. state,
  206. customFields,
  207. methodDict,
  208. dynamicParent,
  209. lexicalParent,
  210. flags,
  211. types,
  212. path_,
  213. name_,
  214. freeVars);
  215. }
  216. }