PageRenderTime 23ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/org.anachronos.clojure.core/src/org/anachronos/clojure/core/parser/antlr/Scope.java

http://clojure-eclipse.googlecode.com/
Java | 82 lines | 47 code | 13 blank | 22 comment | 3 complexity | 09ebcb36b492e55d20121eb864de169f MD5 | raw file
  1. package org.anachronos.clojure.core.parser.antlr;
  2. import java.util.HashMap;
  3. import java.util.HashSet;
  4. import java.util.Map;
  5. import java.util.Set;
  6. /**
  7. * Scope of variables.
  8. *
  9. * @author km
  10. */
  11. public class Scope {
  12. private final Scope parentScope;
  13. private final Set<String> names = new HashSet<String>();
  14. private final Map<String, Arity> functionNameToArity = new HashMap<String, Arity>();
  15. public Scope() {
  16. this(null);
  17. }
  18. private Scope(final Scope parentScope) {
  19. this.parentScope = parentScope;
  20. }
  21. /**
  22. * Creates a new scope with this object as parent scope.
  23. *
  24. * @return new scope
  25. */
  26. public Scope newScope() {
  27. return new Scope(this);
  28. }
  29. /**
  30. * Ends this scope and returns parent scope.
  31. */
  32. public Scope endScope() {
  33. return parentScope;
  34. }
  35. /**
  36. * @param name
  37. * @return true iff. name is defined in this scopes hierachy
  38. */
  39. public boolean isDefined(final String name) {
  40. final boolean contained = names.contains(name);
  41. final boolean containedInHierachy = parentScope != null
  42. && parentScope.isDefined(name);
  43. return contained || containedInHierachy;
  44. }
  45. public boolean isFunction(final String name) {
  46. return functionNameToArity.containsKey(name);
  47. }
  48. public boolean isDefinedArity(final String name, final int arity) {
  49. return getArity(name).isValid(arity);
  50. }
  51. private Arity getArity(final String name) {
  52. return functionNameToArity.get(name);
  53. }
  54. public boolean exceedsArityUpperBound(final String name, final int arity) {
  55. return getArity(name).exceedsUpperbound(arity);
  56. }
  57. /**
  58. * Adds the given declaration to this scope.
  59. *
  60. * @param name
  61. */
  62. public void addVariableDef(String name) {
  63. names.add(name);
  64. }
  65. public void addFunctionDef(String name, int arity, boolean bound) {
  66. names.add(name);
  67. functionNameToArity.put(name, new Arity(arity, bound));
  68. }
  69. }