Search code examples
scalatype-systems

Scala syntax/grammar of type system example?


I'm learning scala.

In scala syntax: https://www.scala-lang.org/files/archive/spec/2.13/13-syntax-summary.html, I read about the type system.

  Type              ::=  FunctionArgTypes ‘=>’ Type
                      |  InfixType [ExistentialClause]
  FunctionArgTypes  ::= InfixType
                      | ‘(’ [ ParamType {‘,’ ParamType } ] ‘)’
  ExistentialClause ::=  ‘forSome’ ‘{’ ExistentialDcl {semi ExistentialDcl} ‘}’
  ExistentialDcl    ::=  ‘type’ TypeDcl
                      |  ‘val’ ValDcl
  InfixType         ::=  CompoundType {id [nl] CompoundType}
  CompoundType      ::=  AnnotType {‘with’ AnnotType} [Refinement]
                      |  Refinement
  AnnotType         ::=  SimpleType {Annotation}
  SimpleType        ::=  SimpleType TypeArgs
                      |  SimpleType ‘#’ id
                      |  StableId
                      |  Path ‘.’ ‘type’
                      |  ‘(’ Types ‘)’
  TypeArgs          ::=  ‘[’ Types ‘]’
  Types             ::=  Type {‘,’ Type}
  Refinement        ::=  [nl] ‘{’ RefineStat {semi RefineStat} ‘}’
  RefineStat        ::=  Dcl
                      |  ‘type’ TypeDef
                      |
  TypePat           ::=  Type

  Ascription        ::=  ‘:’ InfixType
                      |  ‘:’ Annotation {Annotation}
                      |  ‘:’ ‘_’ ‘*’

I can give some examples:

  1. when StableId is Int, and StableId => SimpleType => AnnotType => CompoundType => InfixType => Type, we will get a Type called Int.
  2. when FunctionArgTypes is (), Type is Int, we will get a Type called ()=>Int.
  3. when Type is Array, TypeArgs is [Int], we will get SimpleType = Array[Int], then Type is Array[Int].

I don't understand some of the type system:

  1. What's the InfixType ?
  2. What's the CompoundType ?
  3. What's the Refinement ?
  4. What's the Ascription ?
  5. When will SimpleType derive a SimpleType '#' id, and when will derive '(' Types ')' ?

Is there any examples for scala type system ?


Solution

    1. For example Op in Int Op String is an infix type

      trait Op[A, B]
      
      type T = Int Op String
      
    2. For example Int with String with Boolean is a compound type.

    3. For example { type X } is a type refinement in

      trait MyTrait
      
      type T = MyTrait { type X }
      
    4. For example : Int in 1 : Int is a type ascription.

    5. For example MyTrait#T is a type projection

      trait MyTrait {
        type T
      }
      

      Type

      type T = (Int, String, Boolean)
      

      is a tuple type.