PageRenderTime 60ms CodeModel.GetById 20ms app.highlight 32ms RepoModel.GetById 2ms app.codeStats 0ms

/interpreter/tags/at2dist110511/src/edu/vub/at/objects/natives/NATMethod.java

http://ambienttalk.googlecode.com/
Java | 223 lines | 124 code | 26 blank | 73 comment | 8 complexity | 3aec10a072b0237b8112f8fe540232f0 MD5 | raw file
  1/**
  2 * AmbientTalk/2 Project
  3 * NATMethod.java created on Jul 24, 2006 at 11:30:35 PM
  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 java.util.HashMap;
 31
 32import edu.vub.at.eval.Evaluator;
 33import edu.vub.at.eval.PartialBinder;
 34import edu.vub.at.exceptions.InterpreterException;
 35import edu.vub.at.exceptions.XTypeMismatch;
 36import edu.vub.at.objects.ATClosure;
 37import edu.vub.at.objects.ATContext;
 38import edu.vub.at.objects.ATMethod;
 39import edu.vub.at.objects.ATObject;
 40import edu.vub.at.objects.ATTable;
 41import edu.vub.at.objects.coercion.NativeTypeTags;
 42import edu.vub.at.objects.grammar.ATBegin;
 43import edu.vub.at.objects.grammar.ATSymbol;
 44import edu.vub.at.objects.mirrors.PrimitiveMethod;
 45import edu.vub.at.objects.natives.grammar.AGSymbol;
 46import edu.vub.at.parser.SourceLocation;
 47import edu.vub.at.util.logging.Logging;
 48import edu.vub.util.TempFieldGenerator;
 49
 50/**
 51 * NATMethod implements methods as named functions which are in fact simply containers
 52 * for a name, a table of arguments and a body.
 53 * 
 54 * @author smostinc
 55 * @author tvcutsem
 56 */
 57public class NATMethod extends NATByCopy implements ATMethod {
 58
 59	private final ATSymbol 	name_;
 60	private final ATTable 	parameters_;
 61	private final ATBegin	body_;
 62	private final ATTable	annotations_;
 63	
 64	// partial function denoting a parameter binding algorithm specialized for this method's parameter list
 65	private final PartialBinder parameterBindingFunction_;
 66	
 67	/** construct a new method. This method may raise an exception if the parameter list is illegal. */
 68	public NATMethod(ATSymbol name, ATTable parameters, ATBegin body, ATTable annotations) throws InterpreterException {
 69		name_ 		= name;
 70		parameters_ = parameters;
 71		body_ 		= body;
 72		annotations_= annotations;
 73		
 74		// calculate the parameter binding strategy to use using partial evaluation
 75		parameterBindingFunction_ =
 76			PartialBinder.calculateResidual(name_.base_text().asNativeText().javaValue, parameters);
 77	}
 78	
 79	/**
 80	 * Constructor to be used by primitive methods only.
 81	 */
 82	protected NATMethod(ATSymbol name, ATTable parameters, PrimitiveMethod.PrimitiveBody body, ATTable annotations) {
 83		name_ 		= name;
 84		parameters_ = parameters;
 85		body_ 		= body;
 86		annotations_= annotations;
 87		
 88		PartialBinder parameterBindingFunction;
 89		try {
 90			// calculate the parameter binding strategy to use using partial evaluation
 91			parameterBindingFunction = PartialBinder.calculateResidual(name_.base_text().asNativeText().javaValue, parameters);
 92		} catch (InterpreterException e) {
 93			parameterBindingFunction = null;
 94			// this indicates a bug, primitive methods should not contain erroneous parameter lists
 95			Logging.VirtualMachine_LOG.fatal("error creating primitive method: ",e);
 96		}
 97		parameterBindingFunction_ = parameterBindingFunction;
 98	}
 99
100	public ATClosure base_wrap(ATObject lexicalScope, ATObject dynamicReceiver) throws InterpreterException {
101		NATClosure clo = new NATClosure(this, lexicalScope, dynamicReceiver);
102		// make the closure inherit its source location from this method
103		clo.impl_setLocation(this.impl_getLocation());
104		return clo;
105	}
106	
107	public ATSymbol base_name() {
108		return name_;
109	}
110
111	public ATTable base_parameters() {
112		return parameters_;
113	}
114
115	public ATBegin base_bodyExpression() {
116		return body_;
117	}
118	
119	public ATTable base_annotations() throws InterpreterException {
120		return annotations_;
121	}
122	
123	/**
124	 * To apply a function, first bind its parameters to the evaluated arguments within a new call frame.
125	 * This call frame is lexically nested within the current lexical scope.
126	 * 
127	 * This method is invoked via the following paths:
128	 *  - either by directly 'calling a function', in which case this method is applied via NATClosure.base_apply.
129	 *    The closure ensures that the context used is the lexical scope, not the dynamic scope of invocation.
130	 *  - or by 'invoking a method' through an object, in which case this method is applied via NATObject.meta_invoke.
131	 *    The enclosing object ensures that the context is properly initialized with the implementor, the dynamic receiver
132	 *    and the implementor's parent.
133	 * 
134	 * @param arguments the evaluated actual arguments
135	 * @param ctx the context in which to evaluate the method body, where a call frame will be inserted first
136	 * @return the value of evaluating the function body
137	 */
138	public ATObject base_apply(ATTable arguments, ATContext ctx) throws InterpreterException {
139		NATCallframe cf = new NATCallframe(ctx.base_lexicalScope());
140		ATContext evalCtx = ctx.base_withLexicalEnvironment(cf);
141		PartialBinder.defineParamsForArgs(parameterBindingFunction_, evalCtx, arguments);
142		return body_.meta_eval(evalCtx);
143	}
144	
145	/**
146	 * Applies the method in the context given, without first inserting a call frame to bind parameters.
147	 * Arguments are bound directly in the given lexical scope.
148	 * 
149	 * This method is often invoked via its enclosing closure when used to implement various language
150	 * constructs such as object:, mirror:, extend:with: etc.
151	 * 
152	 * @param arguments the evaluated actual arguments
153	 * @param ctx the context in which to evaluate the method body, to be used as-is
154	 * @return the value of evaluating the function body
155	 */
156	public ATObject base_applyInScope(ATTable arguments, ATContext ctx) throws InterpreterException {
157		PartialBinder.defineParamsForArgs(parameterBindingFunction_, ctx, arguments);
158		return body_.meta_eval(ctx);
159	}
160
161	public NATText meta_print() throws InterpreterException {
162		return NATText.atValue("<method:"+name_.meta_print().javaValue+">");
163	}
164	
165	public NATText impl_asCode(TempFieldGenerator objectMap) throws InterpreterException {
166		if(objectMap.contains(this)) {
167			return objectMap.getName(this);
168		}
169		StringBuffer out = new StringBuffer("");
170		out.append("def "+ name_.meta_print().javaValue);
171		out.append(Evaluator.codeAsList(objectMap, parameters_).javaValue);
172		if(annotations_.base_length().asNativeNumber().javaValue > 0)
173			out.append("@"+annotations_.impl_asCode(objectMap).javaValue);
174		out.append("{" + Evaluator.codeAsStatements(objectMap, body_.base_statements()).javaValue + "}");
175		return NATText.atValue(out.toString());
176	}
177	
178	public NATText impl_asCode(TempFieldGenerator objectMap, boolean asClosure) throws InterpreterException {
179		if(objectMap.contains(this)) {
180			return objectMap.getName(this);
181		}
182		
183		if(asClosure) {
184			StringBuffer out = new StringBuffer("");
185			out.append("{");
186			out.append(Evaluator.codeAsParameterList(objectMap, parameters_).javaValue);
187			out.append(Evaluator.codeAsStatements(objectMap, body_.base_statements()).javaValue + "}");
188			return NATText.atValue(out.toString());
189		} else {
190			return this.impl_asCode(objectMap);
191		}
192	}
193
194	public ATObject meta_clone() throws InterpreterException {
195		return this;
196	}
197
198	public ATMethod asMethod() throws XTypeMismatch {
199		return this;
200	}
201	
202    public ATTable meta_typeTags() throws InterpreterException {
203    	return NATTable.atValue(NATTable.collate(
204    			new ATObject[] { NativeTypeTags._METHOD_, NativeTypeTags._ISOLATE_ },
205    			annotations_.asNativeTable().elements_));
206    }
207    
208	// Debugging API:
209	
210    private SourceLocation loc_;
211    public SourceLocation impl_getLocation() { return loc_; }
212    public void impl_setLocation(SourceLocation loc) {
213    	// overriding the source location of an AmbientTalk object
214    	// is probably the sign of a bug: locations should be single-assignment
215    	// to prevent mutable shared-state. That is, loc_ is effectively 'final'
216    	if (loc_ == null) {
217        	loc_ = loc;  		
218    	} else {
219    		throw new RuntimeException("Trying to override source location of "+this.toString()+" from "+loc_+" to "+loc);
220    	}
221    }
222
223}