[flang-commits] [flang] [flang] Add parsing and semantics for TYPEOF and CLASSOF type specifiers (PR #188804)

via flang-commits flang-commits at lists.llvm.org
Thu Mar 26 10:45:58 PDT 2026


https://github.com/Ritanya-B-Bharadwaj created https://github.com/llvm/llvm-project/pull/188804

Implements parsing and semantic analysis for the Fortran 2023 TYPEOF and CLASSOF type specifiers (R703). TYPEOF produces the declared type of a data-ref; CLASSOF produces a polymorphic version. Includes constraint checks (C7113–C7118) and tests.

Fixes - https://github.com/llvm/llvm-project/issues/185635

>From 779319ae362b80d0585036f5c016ece0affb26f6 Mon Sep 17 00:00:00 2001
From: Ritanya B Bharadwaj <ritanya.b.bharadwaj at gmail.com>
Date: Thu, 26 Mar 2026 12:33:30 -0500
Subject: [PATCH] [flang]Adding initial support for type and classof

---
 flang/include/flang/Parser/dump-parse-tree.h  |   2 +
 flang/include/flang/Parser/parse-tree.h       |   7 +-
 flang/lib/Parser/Fortran-parsers.cpp          |   9 +-
 flang/lib/Parser/unparse.cpp                  |   6 +
 flang/lib/Semantics/resolve-names.cpp         | 116 ++++++++++++++++++
 flang/test/Parser/typeof-classof-attrs.f90    |  22 ++++
 .../test/Semantics/typeof-classof-errors.f90  |  43 +++++++
 flang/test/Semantics/typeof-classof.f90       |  38 ++++++
 8 files changed, 240 insertions(+), 3 deletions(-)
 create mode 100644 flang/test/Parser/typeof-classof-attrs.f90
 create mode 100644 flang/test/Semantics/typeof-classof-errors.f90
 create mode 100644 flang/test/Semantics/typeof-classof.f90

diff --git a/flang/include/flang/Parser/dump-parse-tree.h b/flang/include/flang/Parser/dump-parse-tree.h
index 84c7b8d2a5349..dfb7fa30e20b6 100644
--- a/flang/include/flang/Parser/dump-parse-tree.h
+++ b/flang/include/flang/Parser/dump-parse-tree.h
@@ -284,9 +284,11 @@ class ParseTreeDumper {
   NODE(parser, DeclarationConstruct)
   NODE(parser, DeclarationTypeSpec)
   NODE(DeclarationTypeSpec, Class)
+  NODE(DeclarationTypeSpec, ClassOf)
   NODE(DeclarationTypeSpec, ClassStar)
   NODE(DeclarationTypeSpec, Record)
   NODE(DeclarationTypeSpec, Type)
+  NODE(DeclarationTypeSpec, TypeOf)
   NODE(DeclarationTypeSpec, TypeStar)
   NODE(parser, Default)
   NODE(parser, DeferredCoshapeSpecList)
diff --git a/flang/include/flang/Parser/parse-tree.h b/flang/include/flang/Parser/parse-tree.h
index 4aec99c80bdae..7bbcb7d04d25a 100644
--- a/flang/include/flang/Parser/parse-tree.h
+++ b/flang/include/flang/Parser/parse-tree.h
@@ -759,7 +759,8 @@ struct TypeSpec {
 // R703 declaration-type-spec ->
 //        intrinsic-type-spec | TYPE ( intrinsic-type-spec ) |
 //        TYPE ( derived-type-spec ) | CLASS ( derived-type-spec ) |
-//        CLASS ( * ) | TYPE ( * )
+//        CLASS ( * ) | TYPE ( * ) |
+//        TYPEOF ( data-ref ) | CLASSOF ( data-ref )
 // Legacy extension: RECORD /struct/
 struct DeclarationTypeSpec {
   UNION_CLASS_BOILERPLATE(DeclarationTypeSpec);
@@ -768,8 +769,10 @@ struct DeclarationTypeSpec {
   EMPTY_CLASS(ClassStar);
   EMPTY_CLASS(TypeStar);
   WRAPPER_CLASS(Record, Name);
+  WRAPPER_CLASS(TypeOf, common::Indirection<DataRef>);
+  WRAPPER_CLASS(ClassOf, common::Indirection<DataRef>);
   std::variant<IntrinsicTypeSpec, Type, Class, ClassStar, TypeStar, Record,
-      VectorTypeSpec>
+      VectorTypeSpec, TypeOf, ClassOf>
       u;
 };
 
diff --git a/flang/lib/Parser/Fortran-parsers.cpp b/flang/lib/Parser/Fortran-parsers.cpp
index e86b5e7f79c74..221cae453171c 100644
--- a/flang/lib/Parser/Fortran-parsers.cpp
+++ b/flang/lib/Parser/Fortran-parsers.cpp
@@ -167,7 +167,8 @@ TYPE_CONTEXT_PARSER("type spec"_en_US,
 // R703 declaration-type-spec ->
 //        intrinsic-type-spec | TYPE ( intrinsic-type-spec ) |
 //        TYPE ( derived-type-spec ) | CLASS ( derived-type-spec ) |
-//        CLASS ( * ) | TYPE ( * )
+//        CLASS ( * ) | TYPE ( * ) |
+//        TYPEOF ( data-ref ) | CLASSOF ( data-ref )
 // N.B. It is critical to distribute "parenthesized()" over the alternatives
 // for TYPE (...), rather than putting the alternatives within it, which
 // would fail on "TYPE(real_derived)" with a misrecognition of "real" as an
@@ -176,6 +177,12 @@ TYPE_CONTEXT_PARSER("type spec"_en_US,
 // type (BYTE or DOUBLECOMPLEX), not the extension intrinsic type.
 TYPE_CONTEXT_PARSER("declaration type spec"_en_US,
     construct<DeclarationTypeSpec>(intrinsicTypeSpec) ||
+        "TYPEOF" >>
+            parenthesized(construct<DeclarationTypeSpec>(
+                construct<DeclarationTypeSpec::TypeOf>(indirect(dataRef)))) ||
+        "CLASSOF" >>
+            parenthesized(construct<DeclarationTypeSpec>(
+                construct<DeclarationTypeSpec::ClassOf>(indirect(dataRef)))) ||
         "TYPE" >>
             (parenthesized(construct<DeclarationTypeSpec>(
                  !"DOUBLECOMPLEX"_tok >> !"BYTE"_tok >> intrinsicTypeSpec)) ||
diff --git a/flang/lib/Parser/unparse.cpp b/flang/lib/Parser/unparse.cpp
index 9d01bb74d70d3..10d061cdbcec6 100644
--- a/flang/lib/Parser/unparse.cpp
+++ b/flang/lib/Parser/unparse.cpp
@@ -152,6 +152,12 @@ class UnparseVisitor {
   void Unparse(const DeclarationTypeSpec::Record &x) {
     Word("RECORD/"), Walk(x.v), Put('/');
   }
+  void Unparse(const DeclarationTypeSpec::TypeOf &x) {
+    Word("TYPEOF("), Walk(x.v), Put(')');
+  }
+  void Unparse(const DeclarationTypeSpec::ClassOf &x) {
+    Word("CLASSOF("), Walk(x.v), Put(')');
+  }
   void Before(const IntrinsicTypeSpec::Real &) { // R704
     Word("REAL");
   }
diff --git a/flang/lib/Semantics/resolve-names.cpp b/flang/lib/Semantics/resolve-names.cpp
index 1155fff59a624..5e699794c3045 100644
--- a/flang/lib/Semantics/resolve-names.cpp
+++ b/flang/lib/Semantics/resolve-names.cpp
@@ -1037,6 +1037,8 @@ class DeclarationVisitor : public ArraySpecVisitor,
   bool Pre(const parser::DeclarationTypeSpec::Class &);
   void Post(const parser::DeclarationTypeSpec::Class &);
   void Post(const parser::DeclarationTypeSpec::Record &);
+  bool Pre(const parser::DeclarationTypeSpec::TypeOf &);
+  bool Pre(const parser::DeclarationTypeSpec::ClassOf &);
   void Post(const parser::DerivedTypeSpec &);
   bool Pre(const parser::DerivedTypeDef &);
   bool Pre(const parser::DerivedTypeStmt &);
@@ -1270,6 +1272,7 @@ class DeclarationVisitor : public ArraySpecVisitor,
       const parser::Name &name, Symbol &symbol, Symbol::Flag flag);
   bool CheckForHostAssociatedImplicit(const parser::Name &);
   bool HasCycle(const Symbol &, const Symbol *interface);
+  bool ResolveTypeOfOrClassOf(const parser::DataRef &, bool isClassOf);
   bool MustBeScalar(const Symbol &symbol) const {
     return mustBeScalar_.find(symbol) != mustBeScalar_.end();
   }
@@ -6520,6 +6523,119 @@ void DeclarationVisitor::Post(const parser::DeclarationTypeSpec::Record &rec) {
   }
 }
 
+// TYPEOF and CLASSOF type specifiers
+bool DeclarationVisitor::ResolveTypeOfOrClassOf(
+    const parser::DataRef &dataRef, bool isClassOf) {
+  const char *specName{isClassOf ? "CLASSOF" : "TYPEOF"};
+
+  if (std::holds_alternative<common::Indirection<parser::ArrayElement>>(
+          dataRef.u)) {
+    Say(currStmtSource().value(),
+        "The data-ref in %s must not have subscripts"_err_en_US, specName);
+    return false;
+  }
+  if (std::holds_alternative<common::Indirection<parser::CoindexedNamedObject>>(
+          dataRef.u)) {
+    Say(currStmtSource().value(),
+        "The data-ref in %s must not have an image-selector"_err_en_US,
+        specName);
+    return false;
+  }
+
+  const parser::Name *name{ResolveDataRef(dataRef)};
+  if (!name || !name->symbol) {
+    return false;
+  }
+
+  // C7115: data-ref shall be a data object, not a procedure or type name.
+  const Symbol &ultimate{name->symbol->GetUltimate()};
+  if (!ultimate.has<ObjectEntityDetails>() &&
+      !ultimate.has<AssocEntityDetails>() && !ultimate.has<EntityDetails>()) {
+    Say(name->source, "'%s' in %s must be a data object"_err_en_US,
+        name->source, specName);
+    return false;
+  }
+
+  // C7114: data-ref shall not be a whole assumed-size array.
+  if (IsAssumedSizeArray(ultimate)) {
+    Say(name->source,
+        "The data-ref in %s must not be a whole assumed-size array"_err_en_US,
+        specName);
+    return false;
+  }
+
+  // Get the declared type of the referenced object.
+  const DeclTypeSpec *refType{ultimate.GetType()};
+  if (!refType) {
+    Say(name->source,
+        "Referenced object '%s' does not have a declared type"_err_en_US,
+        name->source);
+    return false;
+  }
+
+  switch (refType->category()) {
+  case DeclTypeSpec::Numeric:
+  case DeclTypeSpec::Logical:
+  case DeclTypeSpec::Character:
+    if (isClassOf) {
+      Say(currStmtSource().value(),
+          "CLASSOF may not be used with an intrinsic-type object"_err_en_US);
+      return false;
+    }
+    SetDeclTypeSpec(*refType);
+    break;
+  case DeclTypeSpec::TypeDerived:
+  case DeclTypeSpec::ClassDerived: {
+    const DerivedTypeSpec &derived{refType->derivedTypeSpec()};
+    if (isClassOf && !IsExtensibleType(&derived)) {
+      Say(currStmtSource().value(),
+          "CLASSOF requires a data-ref of extensible type"_err_en_US);
+      return false;
+    }
+    auto category{
+        isClassOf ? DeclTypeSpec::ClassDerived : DeclTypeSpec::TypeDerived};
+    if (const DeclTypeSpec *extant{
+            currScope().FindInstantiatedDerivedType(derived, category)}) {
+      SetDeclTypeSpec(*extant);
+    } else {
+      DeclTypeSpec &type{
+          currScope().MakeDerivedType(category, DerivedTypeSpec{derived})};
+      DerivedTypeSpec &newDerived{type.derivedTypeSpec()};
+      newDerived.CookParameters(GetFoldingContext());
+      newDerived.EvaluateParameters(context());
+      if (!newDerived.IsForwardReferenced()) {
+        newDerived.Instantiate(currScope());
+      }
+      SetDeclTypeSpec(type);
+    }
+    break;
+  }
+  case DeclTypeSpec::TypeStar:
+  case DeclTypeSpec::ClassStar:
+    // If data-ref is unlimited polymorphic, TYPEOF gives TYPE(*) and
+    // CLASSOF gives CLASS(*).
+    if (isClassOf) {
+      SetDeclTypeSpec(context().globalScope().MakeClassStarType());
+    } else {
+      SetDeclTypeSpec(context().globalScope().MakeTypeStarType());
+    }
+    break;
+  }
+  return true;
+}
+
+bool DeclarationVisitor::Pre(
+    const parser::DeclarationTypeSpec::TypeOf &typeOf) {
+  ResolveTypeOfOrClassOf(typeOf.v.value(), /*isClassOf=*/false);
+  return false;
+}
+
+bool DeclarationVisitor::Pre(
+    const parser::DeclarationTypeSpec::ClassOf &classOf) {
+  ResolveTypeOfOrClassOf(classOf.v.value(), /*isClassOf=*/true);
+  return false;
+}
+
 // The descendents of DerivedTypeDef in the parse tree are visited directly
 // in this Pre() routine so that recursive use of the derived type can be
 // supported in the components.
diff --git a/flang/test/Parser/typeof-classof-attrs.f90 b/flang/test/Parser/typeof-classof-attrs.f90
new file mode 100644
index 0000000000000..d1be75dad8682
--- /dev/null
+++ b/flang/test/Parser/typeof-classof-attrs.f90
@@ -0,0 +1,22 @@
+! RUN: %flang_fc1 -fdebug-unparse-no-sema %s 2>&1 | FileCheck %s
+! Test TYPEOF and CLASSOF with spaces and attributes.
+
+program test_program
+  implicit none
+
+  TYPE :: matrix
+    INTEGER :: v
+  END TYPE
+
+  TYPE(matrix) :: MAT
+
+  !CHECK: TYPEOF(mat), POINTER :: tmat_ptr
+  TYPEOF(MAT), POINTER :: TMAT_PTR
+  !CHECK: TYPEOF(mat), ALLOCATABLE, TARGET :: tmat_allocatable
+  TYPEOF(MAT), ALLOCATABLE, TARGET :: TMAT_ALLOCATABLE
+
+  !CHECK: CLASSOF(mat), POINTER :: cmat_ptr
+  CLASSOF(MAT), POINTER :: CMAT_PTR
+  !CHECK: CLASSOF(mat), ALLOCATABLE, TARGET :: cmat_allocatable
+  CLASSOF(MAT), ALLOCATABLE, TARGET :: CMAT_ALLOCATABLE
+end program
diff --git a/flang/test/Semantics/typeof-classof-errors.f90 b/flang/test/Semantics/typeof-classof-errors.f90
new file mode 100644
index 0000000000000..3e7931446ba14
--- /dev/null
+++ b/flang/test/Semantics/typeof-classof-errors.f90
@@ -0,0 +1,43 @@
+! RUN: %python %S/test_errors.py %s %flang_fc1
+! Test semantic errors for F2023 TYPEOF and CLASSOF type specifiers.
+
+module m
+  type :: base_type
+    integer :: x
+  end type
+  type :: non_extensible_type
+    sequence
+    integer :: x
+  end type
+contains
+  subroutine test_typeof_subscript(a)
+    integer :: a(10)
+    !ERROR: The data-ref in TYPEOF must not have subscripts
+    typeof(a(1)) :: b
+  end subroutine
+
+  subroutine test_classof_intrinsic(a)
+    integer :: a
+    !ERROR: CLASSOF may not be used with an intrinsic-type object
+    classof(a) :: b
+  end subroutine
+
+  subroutine test_typeof_not_found()
+    implicit none
+    !ERROR: No explicit type declared for 'nonexistent'
+    !ERROR: No explicit type declared for 'b'
+    typeof(nonexistent) :: b
+  end subroutine
+
+  subroutine test_classof_non_extensible(a)
+    type(non_extensible_type) :: a
+    !ERROR: CLASSOF requires a data-ref of extensible type
+    classof(a) :: b
+  end subroutine
+
+  subroutine test_typeof_assumed_size(a)
+    integer :: a(*)
+    !ERROR: The data-ref in TYPEOF must not be a whole assumed-size array
+    typeof(a) :: b
+  end subroutine
+end module
diff --git a/flang/test/Semantics/typeof-classof.f90 b/flang/test/Semantics/typeof-classof.f90
new file mode 100644
index 0000000000000..79f7740c24606
--- /dev/null
+++ b/flang/test/Semantics/typeof-classof.f90
@@ -0,0 +1,38 @@
+! RUN: %flang_fc1 -fdebug-unparse %s 2>&1 | FileCheck %s --check-prefix=UNPARSE
+! Test semantics of F2023 TYPEOF and CLASSOF type specifiers.
+
+module m
+  type :: base_type
+    integer :: x
+  end type
+  type, extends(base_type) :: child_type
+    integer :: y
+  end type
+contains
+  subroutine test_typeof_derived(a, b)
+    type(base_type) :: a
+    type(child_type) :: b
+    !UNPARSE: TYPEOF(a) :: c
+    typeof(a) :: c
+    !UNPARSE: TYPEOF(b) :: d
+    typeof(b) :: d
+  end subroutine
+
+  subroutine test_typeof_intrinsic(a, b, c)
+    integer :: a
+    real(8) :: b
+    logical :: c
+    !UNPARSE: TYPEOF(a) :: d
+    typeof(a) :: d
+    !UNPARSE: TYPEOF(b) :: e
+    typeof(b) :: e
+    !UNPARSE: TYPEOF(c) :: f
+    typeof(c) :: f
+  end subroutine
+
+  subroutine test_classof(a)
+    class(base_type), intent(in) :: a
+    !UNPARSE: CLASSOF(a), ALLOCATABLE :: b
+    classof(a), allocatable :: b
+  end subroutine
+end module



More information about the flang-commits mailing list