PageRenderTime 23ms CodeModel.GetById 14ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/interpreter/tags/at2-build060407/src/edu/vub/at/objects/natives/NATNamespace.java

http://ambienttalk.googlecode.com/
Java | 209 lines | 101 code | 21 blank | 87 comment | 6 complexity | d6c80d4ca80b3125204d891f67762fce 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.ATObject;
 37import edu.vub.at.objects.ATStripe;
 38import edu.vub.at.objects.grammar.ATSymbol;
 39import edu.vub.at.objects.mirrors.Reflection;
 40import edu.vub.at.parser.NATParser;
 41
 42import java.io.File;
 43import java.io.IOException;
 44import java.util.LinkedList;
 45import java.util.Vector;
 46
 47/**
 48 * Instances of the class NATNamespace represent namespace objects.
 49 * 
 50 * Namespace objects act as regular AmbientTalk objects with the following differences and conventions:
 51 *  - Behaviourally, a namespace object is mirrored by a mirror whose doesNotUnderstand
 52 *    method reacts differently from the standard semantics of raising a 'selector not found' exception.
 53 *  - Structurally, a namespace has the lexical root as its lexical parent and the dynamic root as its dynamic parent.
 54 *    Furthermore, a namespace object encapsulates an absolute file system path and a relative 'path name'.
 55 *    The name should correspond to a portion of the tail of the absolute path.
 56 *    These variables are not visible to AmbientTalk code.
 57 *         
 58 * When a slot is looked up in a namespace NS for a path P (via meta_select) and not found, the namespace object
 59 * queries the local file system to see whether the selector corresponds to a directory or file in the
 60 * directory P. Either the selector:
 61 *  - corresponds to a directory, in which case the missing slot is bound to a new namespace object corresponding to the path P/selector
 62 *  - corresponds to a file named selector.at, in which case:
 63 *    1) the slot is temporarily bound to nil
 64 *       (this is to prevent loops when the code to be evaluated would refer to itself;
 65 *        it also means there can be no circular dependencies, because referring to a slot still under construction yields nil)
 66 *    2) a new object FS (the 'file scope') is created.
 67 *       This object acts as the local scope for the file and has access to its 'enclosing' namespace via the '~' slot.
 68 *       Hence, it can refer to other files in the 'current directory' using ~.filename
 69 *    3) the code in the file is loaded and evaluated in the context (current=FS, self=FS, super=FS.parent=dynroot)
 70 *    4) the result of the evaluated code is bound to the missing slot.
 71 *       The next time the slot is queried for in the namespace, the value is immediately returned. This prevents
 72 *       files from being loaded twice.
 73 *  - does not correspond to any file or directory, resulting in a selector not found exception as usual.
 74 * 
 75 * @author tvcutsem
 76 * @author smostinc
 77 */
 78public final class NATNamespace extends NATObject {
 79
 80	private static final String _AT_EXT_ = ".at";
 81	private final File path_;
 82	private final String name_;
 83	
 84	/**
 85	 * A namespace object encapsulates a given absolute path and represents the given relative path.
 86	 * 
 87	 * @param name the name of this namespace (corresponding to a certain depth to the tail of the absolute path)
 88	 * @param path an absolute path referring to a local file system directory.
 89	 */
 90	public NATNamespace(String name, File path) {
 91		super();
 92		name_ = name;
 93		path_ = path;
 94	}
 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			  ATStripe[] stripes,
107			  File path,
108			  String name) throws InterpreterException {
109	  super(map, state, customFields, methodDict, dynamicParent, lexicalParent, flags, stripes);
110	  path_ = path;
111	  name_ = name;
112	}
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 ATObject 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		
123		// first, try to see if the file exists and corresponds to a directory
124		File dir = new File(path_, javaSelector);
125		if (dir.exists() && dir.isDirectory()) {
126             // create a new namespace object for this directory
127			NATNamespace childNS = new NATNamespace(name_ + "/" + javaSelector, dir);
128
129			// bind the new child namespace to the selector
130			this.meta_defineField(selector, childNS);
131			return childNS;
132				
133		} else {
134			// try to see if a file with extension .at exists corresponding to the selector
135			File src = new File(path_, javaSelector + _AT_EXT_);
136			if (src.exists() && src.isFile()) {
137			
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, NATNil._INSTANCE_);
140				
141	             // create a new file scope object for this file
142				NATObject fileScope = createFileScopeFor(this);
143				
144				try {
145                     // load the code from the file
146					String code = Evaluator.loadContentOfFile(src);
147				
148				    // construct the proper evaluation context for the code
149				    NATContext ctx = new NATContext(fileScope, fileScope);
150				    
151				    // parse and evaluate the code in the proper context and bind its result to the missing slot
152					ATAbstractGrammar source = NATParser.parse(src.getName(), code);
153					ATObject result = source.meta_eval(ctx);
154					this.meta_assignField(this, selector, result);
155					
156					return result;
157				} catch (IOException e) {
158					throw new XIOProblem(e);
159				}
160				
161			} else { // neither a matching directory nor a matching file.at were found
162                 // perform the default dNU behaviour, which means raising a 'selector not found' exception
163				return super.meta_doesNotUnderstand(selector);
164			}
165		}
166	}
167
168	public NATText meta_print() throws InterpreterException {
169		return NATText.atValue("<ns:"+name_+">");
170	}
171	
172	public static NATObject createFileScopeFor(NATNamespace ns) {
173		NATObject fileScope = new NATObject();
174		// a fileScope object is empty, save for a reference to its creating namespace
175		try {
176			fileScope.meta_defineField(Evaluator._CURNS_SYM_, ns);
177		} catch (XDuplicateSlot e) {
178			// impossible: the object is empty
179			e.printStackTrace();
180		} catch (XTypeMismatch e) {
181			// impossible: the given selector is native
182			e.printStackTrace();
183		} catch (InterpreterException e) {
184			// impossible : call cannot be intercepted : namespaces are not mirages
185			e.printStackTrace();			
186		}
187		return fileScope;
188	}
189	
190	protected NATObject createClone(FieldMap map,
191			  Vector state,
192			  LinkedList customFields,
193			  MethodDictionary methodDict,
194			  ATObject dynamicParent,
195			  ATObject lexicalParent,
196			  byte flags, ATStripe[] stripes) throws InterpreterException {
197      return new NATNamespace(map,
198    		  				    state,
199    		  				    customFields,
200    		  				    methodDict,
201    		  				    dynamicParent,
202    		  				    lexicalParent,
203    		  				    flags,
204    		  				    stripes,
205    		  				    path_,
206    		  				    name_);
207	}
208	
209}