binders.scala
来自「JAVA 语言的函数式编程扩展」· SCALA 代码 · 共 358 行 · 第 1/2 页
SCALA
358 行
/* __ *\** ________ ___ / / ___ Scala API **** / __/ __// _ | / / / _ | (c) 2006-2008, LAMP/EPFL **** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **** /____/\___/_/ |_/____/_/ | | **** |/ **\* */package scala.util.parsing.astimport scala.collection.mutable.Map//DISCLAIMER: this code is highly experimental! // TODO: avoid clashes when substituting // TODO: check binders in the same scope are distinct/** <p> * This trait provides the core Scrap-Your-Boilerplate abstractions as * well as implementations for common datatypes. * </p> * <p> * Based on Ralph Laemmel's <a target="_top" * href="http://homepages.cwi.nl/~ralf/publications.html">SYB papers</a>. * </p> * * @author Adriaan Moors */trait Mappable { trait Mapper { def apply[T <% Mappable[T]](x: T): T } /* TODO: having type `Forall T. T => T' is too strict: sometimes we want to allow `Forall T >: precision. T => T' for some type `precision', so that, beneath a certain threshold, we have some leeway. concretely: to use gmap for substitution, we simply require that ast nodes are mapped to ast nodes, we can't require that the type is preserved precisely: a Name may map to e.g., a MethodCall */ trait Mappable[T] { // one-layer traversal def gmap(f: Mapper): T // everywhere f x = f (gmapT (everywhere f) x) def everywhere(f: Mapper)(implicit c: T => Mappable[T]): T = f(gmap(new Mapper { def apply[T <% Mappable[T]](x: T): T = x.everywhere(f)})) } implicit def StringIsMappable(s: String): Mappable[String] = new Mappable[String] { def gmap(f: Mapper): String = f(s) } implicit def ListIsMappable[t <% Mappable[t]](xs: List[t]): Mappable[List[t]] = new Mappable[List[t]] { def gmap(f: Mapper): List[t] = (for (x <- xs) yield f(x)).toList } implicit def OptionIsMappable[t <% Mappable[t]](xs: Option[t]): Mappable[Option[t]] = new Mappable[Option[t]] { def gmap(f: Mapper): Option[t] = (for (x <- xs) yield f(x)) }}/** <p> * This component provides functionality for enforcing variable binding * during parse-time. * </p> * <p> * When parsing simple languages, like Featherweight Scala, these parser * combinators will fully enforce the binding discipline. When names are * allowed to be left unqualified, these mechanisms would have to be * complemented by an extra phase that resolves names that couldn't be * resolved using the naive binding rules. (Maybe some machinery to * model `implicit' binders (e.g., `this' and imported qualifiers) * and selection on a binder will suffice?) * </p> * * @author Adriaan Moors */trait Binders extends AbstractSyntax with Mappable { /** A `Scope' keeps track of one or more syntactic elements that represent bound names. * The elements it contains share the same scope and must all be distinct (wrt. ==) * * A `NameElement' `n' in the AST that is conceptually bound by a `Scope' `s', is replaced by a * `BoundElement(n, s)'. (For example, in `val x:Int=x+1', the first `x' is modelled by a * Scope `s' that contains `x' and the second `x' is represented by a `BoundElement(`x', s)') * The term (`x+1') in scope of the Scope becomes an `UnderBinder(s, `x+1'). * * A `NameElement' `n' is bound by a `Scope' `s' if it is wrapped as a `BoundElement(`n', s)', and * `s' has a binder element that is semantically equal (`equals' or `==') to `n'. * * A `Scope' is represented textually by its list of binder elements, followed by the scope's `id'. * For example: `[x, y]!1' represents the scope with `id' `1' and binder elements `x' and `y'. * (`id' is solely used for this textual representation.) */ class Scope[binderType <: NameElement] extends Iterable[binderType]{ private val substitution: Map[binderType, Element] = new scala.collection.jcl.LinkedHashMap[binderType, Element] // a LinkedHashMap is ordered by insertion order -- important! /** Returns a unique number identifying this Scope (only used for representation purposes). */ val id: Int = _Binder.genId /** Returns the binders in this scope. * For a typical let-binding, this is just the variable name. For an argument list to a method body, * there is one binder per formal argument. */ def elements = substitution.keys /** Return the `i'th binder in this scope.*/ def apply(i: Int): binderType = elements.toList(i) /** Returns true if this container has a binder equal (==) to `b' */ def binds(b: binderType): Boolean = substitution.contains(b) def indexFor(b: binderType): Option[Int] = { val iter = elements.counted for (that <- iter) { if (that.name == b.name) // TODO: why do name equals and structural equals differ? return Some(iter.count) else Console.println(that+"!="+b) } None } /** Adds a new binder. * (e.g. the variable name in a local variable declaration) * * @param b a new binder that is distinct from the existing binders in this scope, * and shares their conceptual scope * @pre canAddBinder(b) * @post binds(b) * @post getElementFor(b) eq b */ def addBinder(b: binderType) { substitution += Pair(b, b) } /** `canAddElement' indicates whether `b' may be added to this scope. * * TODO: strengthen this condition so that no binders may be added after this scope has been * linked to its `UnderBinder' (i.e., while parsing, BoundElements may be added to the Scope * associated to the UnderBinder, but after that, no changes are allowed, except for substitution)? * * @returns true if `b' had not been added yet */ def canAddBinder(b: binderType): Boolean = !binds(b) /** ``Replaces'' the bound occurrences of a contained binder by their new value. * The bound occurrences of `b' are not actually replaced; the scope keeps track * of a substitution that maps every binder to its current value. Since a `BoundElement' is * a proxy for the element it is bound to by its binder, `substitute' may thus be thought of * as replacing all the bound occurrences of the given binder `b' by their new value `value'. * * @param b the binder whose bound occurrences should be given a new value * @param value the new value for the bound occurrences of `b' * @pre binds(b) * @post getElementFor(b) eq value */ def substitute(b: binderType, value: Element): Unit = substitution(b) = value /** Returns the current value for the bound occurrences of `b'. * * @param b the contained binder whose current value should be returned * @pre binds(b) */ def getElementFor(b: binderType): Element = substitution(b) override def toString: String = elements.toList.mkString("[",", ","]")+"!"+id // TODO show substitution? /** Returns a list of strings that represent the binder elements, each tagged with this scope's id.*/ def bindersToString: List[String] = (for(val b <- elements) yield b+"!"+id).toList /** Return a new inheriting scope that won't check whether binding is respected until the scope is left (so as to support forward references) **/ def allowForwardRef: Scope[binderType] = this // TODO /** Return a nested scope -- binders entered into it won't be visible in this scope, but if this scope allows forward references, the binding in the returned scope also does, and thus the check that all variables are bound is deferred until this scope is left **/ def nested: Scope[binderType] = this // TODO def onEnter {}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?