PageRenderTime 34ms CodeModel.GetById 19ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/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 */
 28package edu.vub.at.objects.natives;
 29
 30import edu.vub.at.eval.Evaluator;
 31import edu.vub.at.exceptions.InterpreterException;
 32import edu.vub.at.exceptions.XDuplicateSlot;
 33import edu.vub.at.exceptions.XIOProblem;
 34import edu.vub.at.exceptions.XTypeMismatch;
 35import edu.vub.at.objects.ATAbstractGrammar;
 36import edu.vub.at.objects.ATClosure;
 37import edu.vub.at.objects.ATObject;
 38import edu.vub.at.objects.ATTable;
 39import edu.vub.at.objects.ATTypeTag;
 40import edu.vub.at.objects.coercion.NativeTypeTags;
 41import edu.vub.at.objects.grammar.ATSymbol;
 42import edu.vub.at.objects.mirrors.NativeClosure;
 43import edu.vub.at.objects.mirrors.Reflection;
 44import edu.vub.at.parser.NATParser;
 45import edu.vub.util.TempFieldGenerator;
 46
 47import java.io.File;
 48import java.io.IOException;
 49import java.util.LinkedList;
 50import java.util.Set;
 51import java.util.Vector;
 52
 53/**
 54 * Instances of the class NATNamespace represent namespace objects.
 55 * 
 56 * Namespace objects act as regular AmbientTalk objects with the following differences and conventions:
 57 *  - Behaviourally, a namespace object is mirrored by a mirror whose doesNotUnderstand
 58 *    method reacts differently from the standard semantics of raising a 'selector not found' exception.
 59 *  - Structurally, a namespace has the lexical root as its lexical parent and the dynamic root as its dynamic parent.
 60 *    Furthermore, a namespace object encapsulates an absolute file system path and a relative 'path name'.
 61 *    The name should correspond to a portion of the tail of the absolute path.
 62 *    These variables are not visible to AmbientTalk code.
 63 *         
 64 * When a slot is looked up in a namespace NS for a path P (via meta_select) and not found, the namespace object
 65 * queries the local file system to see whether the selector corresponds to a directory or file in the
 66 * directory P. Either the selector:
 67 *  - corresponds to a directory, in which case the missing slot is bound to a new namespace object corresponding to the path P/selector
 68 *  - corresponds to a file named selector.at, in which case:
 69 *    1) the slot is temporarily bound to nil
 70 *       (this is to prevent loops when the code to be evaluated would refer to itself;
 71 *        it also means there can be no circular dependencies, because referring to a slot still under construction yields nil)
 72 *    2) a new object FS (the 'file scope') is created.
 73 *       This object acts as the local scope for the file and has access to its 'enclosing' namespace via the '~' slot.
 74 *       Hence, it can refer to other files in the 'current directory' using ~.filename
 75 *    3) the code in the file is loaded and evaluated in the context (current=FS, self=FS, super=FS.parent=dynroot)
 76 *    4) the result of the evaluated code is bound to the missing slot.
 77 *       The next time the slot is queried for in the namespace, the value is immediately returned. This prevents
 78 *       files from being loaded twice.
 79 *  - does not correspond to any file or directory, resulting in a selector not found exception as usual.
 80 * 
 81 * @author tvcutsem
 82 * @author smostinc
 83 */
 84public final class NATNamespace extends NATObject {
 85
 86	private static final String _AT_EXT_ = ".at";
 87	private final File path_;
 88	private final String name_;
 89	
 90	/**
 91	 * A namespace object encapsulates a given absolute path and represents the given relative path.
 92	 * 
 93	 * @param name the name of this namespace (corresponding to a certain depth to the tail of the absolute path)
 94	 * @param path an absolute path referring to a local file system directory.
 95	 */
 96	public NATNamespace(String name, File path) {
 97		super();
 98		name_ = name;
 99		path_ = path;
100	}
101	
102	/**
103	 * Private constructor used only for cloning
104	 */
105	private NATNamespace(FieldMap map,
106			  Vector state,
107			  LinkedList customFields,
108			  MethodDictionary methodDict,
109			  ATObject dynamicParent,
110			  ATObject lexicalParent,
111			  byte flags,
112			  ATTypeTag[] types,
113			  File path,
114			  String name,
115			  Set freeVars) throws InterpreterException {
116	  super(map, state, customFields, methodDict, dynamicParent, lexicalParent, flags, types, freeVars);
117	  path_ = path;
118	  name_ = name;
119	}
120	
121	/**
122	 * For a namespace object, doesNotUnderstand triggers the querying of the local file system
123	 * to load files corresponding to the missing selector.
124	 */
125	public ATClosure meta_doesNotUnderstand(ATSymbol selector) throws InterpreterException {
126		// first, convert the AmbientTalk name to a Java selector. Java selectors are always valid filenames because
127		// they do not contain special operator characters
128		String javaSelector = Reflection.upSelector(selector);
129		
130		// first, try to see if the file exists and corresponds to a directory
131		File dir = new File(path_, javaSelector);
132		if (dir.exists() && dir.isDirectory()) {
133             // create a new namespace object for this directory
134			final NATNamespace childNS = new NATNamespace(name_ + File.separator + javaSelector, dir);
135
136			// bind the new child namespace to the selector
137			this.meta_defineField(selector, childNS);
138			return new NativeClosure(this) {
139				public ATObject base_apply(ATTable args) {
140					return childNS;
141				}
142			};
143		} else {
144			// try to see if a file with extension .at exists corresponding to the selector
145			File src = new File(path_, javaSelector + _AT_EXT_);
146			if (src.exists() && src.isFile()) {
147			
148                 // bind the missing slot to nil to prevent calling this dNU recursively when evaluating the code in the file
149				this.meta_defineField(selector, Evaluator.getNil());
150				
151	             // create a new file scope object for this file
152				NATObject fileScope = createFileScopeFor(this);
153				
154				try {
155                     // load the code from the file
156					String code = Evaluator.loadContentOfFile(src);
157				
158				    // construct the proper evaluation context for the code
159				    NATContext ctx = new NATContext(fileScope, fileScope);
160				    
161				    // parse and evaluate the code in the proper context and bind its result to the missing slot
162					ATAbstractGrammar source = NATParser.parse(src.getAbsolutePath(), code);
163					final ATObject result = source.meta_eval(ctx);
164					this.impl_invokeMutator(this, selector.asAssignmentSymbol(), NATTable.of(result));
165					//this.meta_assignField(this, selector, result);
166					
167					// keeping up with the UAP: if the return value of a module is
168					// a function, the function itself is returned (and most presumably
169					// applied immediately). This allows modules to be parameterized easily.
170					if (result.meta_isTaggedAs(NativeTypeTags._CLOSURE_).asNativeBoolean().javaValue) {
171						return result.asClosure();
172					} else {
173						return new NativeClosure(this) {
174							public ATObject base_apply(ATTable args) {
175								return result;
176							}
177						};	
178					}
179				} catch (IOException e) {
180					throw new XIOProblem(e);
181				}
182				
183			} else { // neither a matching directory nor a matching file.at were found
184                 // perform the default dNU behaviour, which means raising a 'selector not found' exception
185				return super.meta_doesNotUnderstand(selector);
186			}
187		}
188	}
189
190	public NATText meta_print() throws InterpreterException {
191		return NATText.atValue("<ns:"+name_+">");
192	}
193	
194	public NATText impl_asCode(TempFieldGenerator objectMap) {
195		return NATText.atValue("/" + name_.replace('/', '.'));
196		
197	}
198	
199	public static NATObject createFileScopeFor(NATNamespace ns) {
200		NATObject fileScope = new NATObject();
201		// a fileScope object is empty, save for a reference to its creating namespace
202		try {
203			fileScope.meta_defineField(Evaluator._CURNS_SYM_, ns);
204		} catch (XDuplicateSlot e) {
205			// impossible: the object is empty
206			e.printStackTrace();
207		} catch (XTypeMismatch e) {
208			// impossible: the given selector is native
209			e.printStackTrace();
210		} catch (InterpreterException e) {
211			// impossible : call cannot be intercepted : namespaces are not mirages
212			e.printStackTrace();			
213		}
214		return fileScope;
215	}
216	
217	protected NATObject createClone(FieldMap map,
218			  Vector state,
219			  LinkedList customFields,
220			  MethodDictionary methodDict,
221			  ATObject dynamicParent,
222			  ATObject lexicalParent,
223			  byte flags, ATTypeTag[] types,
224			  Set freeVars) throws InterpreterException {
225      return new NATNamespace(map,
226    		  				    state,
227    		  				    customFields,
228    		  				    methodDict,
229    		  				    dynamicParent,
230    		  				    lexicalParent,
231    		  				    flags,
232    		  				    types,
233    		  				    path_,
234    		  				    name_,
235    		  				    freeVars);
236	}
237	
238}