Use of the term "Abstract Syntax Tree"

I'm trying to further my understanding of Scala, and one thing that has me puzzled is the use of the term Abstract Syntax Tree (aka AST).

In many places now I have seen programmers use the term AST to describe some code. The following example is from the book "Advanced Scala" by Noel Welsh and Dave Gurnell in the section describing the Type Class pattern.

// Define a very simple JSON AST
sealed trait Json
final case class JsObject(get: Map[String, Json]) extends Json
final case class JsString(get: String) extends Json
final case class JsNumber(get: Double) extends Json

I guess the above is a tree, albeit a very shallow one.

                 Json
                  |
      +-----------+-+-----------+
      |             |           |
  JsObject      JsString      JsNumber

My understanding of an AST is generally in the context of a compiler which creates an AST from the the Concrete Syntax Tree that represents the code (Code Syntaxt Analysis -> Concrete Syntax Tree -> Abstract Syntax Tree).

Why is the above an AST?

I know that the authors are not using the term in the context of the syntax analysis of a compiler but since AST is generally used to mean an abstract representation of code, why would anyone use the term to describe some actual code?


It's not called an AST because of the inheritance tree. It's called an AST because it's a tree structure and it represents the syntax of JSON.

To see how it is a tree structure, consider the following example:

{"a": 42, "b": {"x": "y"}}

This will be parsed to the following object:

JsObject(Map(
    "a" -> JsInt(42),
    "b" -> JsObject(Map(
      "x" -> JsString("y")
    ))
))

Which represents the following tree:

         Object
    "a" /       "b"
      Int    Object
       |        | "x"
       42    String
                |
               "y"

This is an abstract syntax tree of the above JSON string.

I know that the authors are not using the term in the context of the syntax analysis of a compiler

Not of a compiler, but they are using it in the context of analyzing the abstract syntax of JSON.

链接地址: http://www.djcxy.com/p/68218.html

上一篇: Java库存程序问题

下一篇: 使用术语“抽象语法树”