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