/-
Copyright (c) 2021 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Authors: Wojciech Nawrocki, Marc Huisinga
-/
import Lean.DeclarationRange

import Lean.Data.Json
import Lean.Data.Lsp

import Lean.Server.FileSource
import Lean.Server.FileWorker.Utils

import Lean.Server.Rpc.Basic

/-! We maintain a global map of LSP request handlers. This allows user code such as plugins
to register its own handlers, for example to support ITP functionality such as goal state
visualization.

For details of how to register one, see `registerLspRequestHandler`. -/

namespace Lean.Server

structure RequestError where
  code    : JsonRpc.ErrorCode
  message : String

namespace RequestError
open JsonRpc

def fileChanged : RequestError :=
  { code := ErrorCode.contentModified
    message := "File changed." }

def methodNotFound (method : String) : RequestError :=
  { code := ErrorCode.methodNotFound
    message := s!"No request handler found for '{method}'" }

instance : Coe IO.Error RequestError where
  coe e := { code := ErrorCode.internalError
             message := toString e }

def toLspResponseError (id : RequestID) (e : RequestError) : ResponseError Unit :=
  { id := id
    code := e.code
    message := e.message }

end RequestError

def parseRequestParams (paramType : Type) [FromJson paramType] (params : Json)
    : Except RequestError paramType :=
  fromJson? params |>.mapError fun inner =>
    { code := JsonRpc.ErrorCode.parseError
      message := s!"Cannot parse request params: {params.compress}\n{inner}" }

structure RequestContext where
  rpcSessions   : Std.RBMap UInt64 (IO.Ref FileWorker.RpcSession) compare
  srcSearchPath : SearchPath
  doc           : FileWorker.EditableDocument
  hLog          : IO.FS.Stream
  initParams    : Lsp.InitializeParams

abbrev RequestTask α := Task (Except RequestError α)
/-- Workers execute request handlers in this monad. -/
abbrev RequestM := ReaderT RequestContext <| EIO RequestError

instance : Inhabited (RequestM α) :=
  ⟨throw ("executing Inhabited instance?!" : RequestError)⟩

instance : MonadLift IO RequestM where
  monadLift x := x.toEIO fun e => (e : RequestError)

namespace RequestM
open FileWorker
open Snapshots

def readDoc : RequestM EditableDocument := fun rc =>
  return rc.doc

def asTask (t : RequestM α) : RequestM (RequestTask α) := fun rc => do
  let t ← EIO.asTask <| t rc
  return t.map liftExcept

def mapTask (t : Task α) (f : α → RequestM β) : RequestM (RequestTask β) := fun rc => do
  let t ← EIO.mapTask (f · rc) t
  return t.map liftExcept

def bindTask (t : Task α) (f : α → RequestM (RequestTask β)) : RequestM (RequestTask β) := fun rc => do
  EIO.bindTask t (f · rc)

/-- Create a task which waits for the first snapshot matching `p`, handles various errors,
and if a matching snapshot was found executes `x` with it. If not found, the task executes
`notFoundX`. -/
def withWaitFindSnap (doc : EditableDocument) (p : Snapshot → Bool)
  (notFoundX : RequestM β)
  (x : Snapshot → RequestM β)
    : RequestM (RequestTask β) := do
  let findTask ← doc.allSnaps.waitFind? p
  mapTask findTask fun
    /- The elaboration task that we're waiting for may be aborted if the file contents change.
    In that case, we reply with the `fileChanged` error. Thanks to this, the server doesn't
    get bogged down in requests for an old state of the document. -/
    | Except.error FileWorker.ElabTaskError.aborted =>
      throwThe RequestError RequestError.fileChanged
    | Except.error (FileWorker.ElabTaskError.ioError e) =>
      throw (e : RequestError)
    | Except.ok none => notFoundX
    | Except.ok (some snap) => x snap

end RequestM

/- The global request handlers table. -/
section HandlerTable
open Lsp

structure RequestHandler where
  fileSource : Json → Except RequestError Lsp.DocumentUri
  handle : Json → RequestM (RequestTask Json)

builtin_initialize requestHandlers : IO.Ref (Std.PersistentHashMap String RequestHandler) ←
  IO.mkRef {}

/-- NB: This method may only be called in `builtin_initialize` blocks.

A registration consists of:
- a type of JSON-parsable request data `paramType`
- a `FileSource` instance for it so the system knows where to route requests
- a type of JSON-serializable response data `respType`
- an actual `handler` which runs in the `RequestM` monad and is expected
  to produce an asynchronous `RequestTask` which does any waiting/computation

A handler task may be cancelled at any time, so it should check the cancellation token when possible
to handle this cooperatively. Any exceptions thrown in a request handler will be reported to the client
as LSP error responses. -/
def registerLspRequestHandler (method : String)
    paramType [FromJson paramType] [FileSource paramType]
    respType [ToJson respType]
    (handler : paramType → RequestM (RequestTask respType)) : IO Unit := do
  if !(← IO.initializing) then
    throw <| IO.userError s!"Failed to register LSP request handler for '{method}': only possible during initialization"
  if (← requestHandlers.get).contains method then
    throw <| IO.userError s!"Failed to register LSP request handler for '{method}': already registered"
  let fileSource := fun j =>
    parseRequestParams paramType j |>.map Lsp.fileSource
  let handle := fun j => do
    let params ← liftExcept <| parseRequestParams paramType j
    let t ← handler params
    pure <| t.map <| Except.map ToJson.toJson

  requestHandlers.modify fun rhs => rhs.insert method { fileSource, handle }

def lookupLspRequestHandler (method : String) : IO (Option RequestHandler) :=
  return (← requestHandlers.get).find? method

/-- NB: This method may only be called in `builtin_initialize` blocks.

Register another handler to invoke after the last one registered for a method.
At least one handler for the method must have already been registered to perform
chaining.

For more details on the registration of a handler, see `registerLspRequestHandler`. -/
def chainLspRequestHandler (method : String)
    paramType [FromJson paramType]
    respType [FromJson respType] [ToJson respType]
    (handler : paramType → RequestTask respType → RequestM (RequestTask respType)) : IO Unit := do
  if !(← IO.initializing) then
    throw <| IO.userError s!"Failed to chain LSP request handler for '{method}': only possible during initialization"
  if let some oldHandler ← lookupLspRequestHandler method then
    let handle := fun j => do
      let t ← oldHandler.handle j
      let t := t.map fun x => x.bind fun j => FromJson.fromJson? j |>.mapError fun e =>
        IO.userError s!"Failed to parse original LSP response for `{method}` when chaining: {e}"
      let params ← liftExcept <| parseRequestParams paramType j
      let t ← handler params t
      pure <| t.map <| Except.map ToJson.toJson

    requestHandlers.modify fun rhs => rhs.insert method {oldHandler with handle}
  else
    throw <| IO.userError s!"Failed to chain LSP request handler for '{method}': no initial handler registered"

def routeLspRequest (method : String) (params : Json) : IO (Except RequestError DocumentUri) := do
  match (← lookupLspRequestHandler method) with
  | none => return Except.error <| RequestError.methodNotFound method
  | some rh => return rh.fileSource params

def handleLspRequest (method : String) (params : Json) : RequestM (RequestTask Json) := do
  match (← lookupLspRequestHandler method) with
  | none => throw (s!"internal server error: request '{method}' routed through watchdog but unknown in worker; are both using the same plugins?" : RequestError)
  | some rh => rh.handle params

end HandlerTable
end Lean.Server


/-
Copyright (c) 2021 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Authors: Wojciech Nawrocki, Marc Huisinga
-/
import Lean.DeclarationRange

import Lean.Data.Json
import Lean.Data.Lsp

import Lean.Server.FileSource
import Lean.Server.FileWorker.Utils

import Lean.Server.Rpc.Basic

/-! We maintain a global map of LSP request handlers. This allows user code such as plugins
to register its own handlers, for example to support ITP functionality such as goal state
visualization.

For details of how to register one, see `registerLspRequestHandler`. -/

namespace Lean.Server

structure RequestError where
  code    : JsonRpc.ErrorCode
  message : String

namespace RequestError
open JsonRpc

def fileChanged : RequestError :=
  { code := ErrorCode.contentModified
    message := "File changed." }

def methodNotFound (method : String) : RequestError :=
  { code := ErrorCode.methodNotFound
    message := s!"No request handler found for '{method}'" }

instance : Coe IO.Error RequestError where
  coe e := { code := ErrorCode.internalError
             message := toString e }

def toLspResponseError (id : RequestID) (e : RequestError) : ResponseError Unit :=
  { id := id
    code := e.code
    message := e.message }

end RequestError

def parseRequestParams (paramType : Type) [FromJson paramType] (params : Json)
    : Except RequestError paramType :=
  fromJson? params |>.mapError fun inner =>
    { code := JsonRpc.ErrorCode.parseError
      message := s!"Cannot parse request params: {params.compress}\n{inner}" }

structure RequestContext where
  rpcSessions   : Std.RBMap UInt64 (IO.Ref FileWorker.RpcSession) compare
  srcSearchPath : SearchPath
  doc           : FileWorker.EditableDocument
  hLog          : IO.FS.Stream

abbrev RequestTask α := Task (Except RequestError α)
/-- Workers execute request handlers in this monad. -/
abbrev RequestM := ReaderT RequestContext <| ExceptT RequestError IO

instance : Inhabited (RequestM α) :=
  ⟨throwThe IO.Error "executing Inhabited instance?!"⟩

namespace RequestM
open FileWorker
open Snapshots

def readDoc : RequestM EditableDocument := fun rc =>
  rc.doc

def asTask (t : RequestM α) : RequestM (RequestTask α) := fun rc => do
  let t ← IO.asTask <| t rc
  return t.map fun
    | Except.error e => throwThe RequestError e
    | Except.ok v    => v

def mapTask (t : Task α) (f : α → RequestM β) : RequestM (RequestTask β) := fun rc => do
  let t ← (IO.mapTask · t) fun a => f a rc
  return t.map fun
    | Except.error e => throwThe RequestError e
    | Except.ok v    => v

def bindTask (t : Task α) (f : α → RequestM (RequestTask β)) : RequestM (RequestTask β) := fun rc => do
  let t ← IO.bindTask t fun a => do
    match (← f a rc) with
    | Except.error e => return Task.pure <| Except.ok <| Except.error e
    | Except.ok t    => return t.map Except.ok
  return t.map fun
    | Except.error e => throwThe RequestError e
    | Except.ok v    => v

/-- Create a task which waits for a snapshot matching `p`, handles various errors,
and if a matching snapshot was found executes `x` with it. If not found, the task
executes `notFoundX`. -/
def withWaitFindSnap (doc : EditableDocument) (p : Snapshot → Bool)
  (notFoundX : RequestM β)
  (x : Snapshot → RequestM β)
    : RequestM (RequestTask β) := do
  let findTask ← doc.cmdSnaps.waitFind? p
  mapTask findTask fun
    /- The elaboration task that we're waiting for may be aborted if the file contents change.
    In that case, we reply with the `fileChanged` error. Thanks to this, the server doesn't
    get bogged down in requests for an old state of the document. -/
    | Except.error FileWorker.ElabTaskError.aborted =>
      throwThe RequestError RequestError.fileChanged
    | Except.error (FileWorker.ElabTaskError.ioError e) =>
      throwThe IO.Error e
    | Except.error FileWorker.ElabTaskError.eof => notFoundX
    | Except.ok none => notFoundX
    | Except.ok (some snap) => x snap

end RequestM

/- The global request handlers table. -/
section HandlerTable
open Lsp

private structure RequestHandler where
  fileSource : Json → Except RequestError Lsp.DocumentUri
  handle : Json → RequestM (RequestTask Json)

builtin_initialize requestHandlers : IO.Ref (Std.PersistentHashMap String RequestHandler) ←
  IO.mkRef {}

/-- NB: This method may only be called in `builtin_initialize` blocks.

A registration consists of:
- a type of JSON-parsable request data `paramType`
- a `FileSource` instance for it so the system knows where to route requests
- a type of JSON-serializable response data `respType`
- an actual `handler` which runs in the `RequestM` monad and is expected
  to produce an asynchronous `RequestTask` which does any waiting/computation

A handler task may be cancelled at any time, so it should check the cancellation token when possible
to handle this cooperatively. Any exceptions thrown in a request handler will be reported to the client
as LSP error responses. -/
def registerLspRequestHandler (method : String)
    paramType [FromJson paramType] [FileSource paramType]
    respType [ToJson respType]
    (handler : paramType → RequestM (RequestTask respType)) : IO Unit := do
  if !(← IO.initializing) then
    throw <| IO.userError s!"Failed to register LSP request handler for '{method}': only possible during initialization"
  if (←requestHandlers.get).contains method then
    throw <| IO.userError s!"Failed to register LSP request handler for '{method}': already registered"
  let fileSource := fun j =>
    parseRequestParams paramType j |>.map Lsp.fileSource
  let handle := fun j => do
    let params ← parseRequestParams paramType j
    let t ← handler params
    t.map <| Except.map ToJson.toJson

  requestHandlers.modify fun rhs => rhs.insert method { fileSource, handle }

private def lookupLspRequestHandler (method : String) : IO (Option RequestHandler) := do
  (← requestHandlers.get).find? method

def routeLspRequest (method : String) (params : Json) : IO (Except RequestError DocumentUri) := do
  match (← lookupLspRequestHandler method) with
  | none => return Except.error <| RequestError.methodNotFound method
  | some rh => return rh.fileSource params

def handleLspRequest (method : String) (params : Json) : RequestM (RequestTask Json) := do
  match (← lookupLspRequestHandler method) with
  | none => throwThe IO.Error <| IO.userError s!"internal server error: request '{method}' routed through watchdog but unknown in worker; are both using the same plugins?"
  | some rh => rh.handle params

end HandlerTable
end Lean.Server


inductive Foo where
  | a | b | c

def f : Foo → Nat
  | Foo.a => 10
  | Foo.b => 20
  | Foo.c => 35

inductive CXCursorKind where
  | CXCursor_UnexposedDecl
  | CXCursor_StructDecl
  | CXCursor_UnionDecl
  | CXCursor_ClassDecl
  | CXCursor_EnumDecl
  | CXCursor_FieldDecl
  | CXCursor_EnumConstantDecl
  | CXCursor_FunctionDecl
  | CXCursor_VarDecl
  | CXCursor_ParmDecl
  | CXCursor_ObjCInterfaceDecl
  | CXCursor_ObjCCategoryDecl
  | CXCursor_ObjCProtocolDecl
  | CXCursor_ObjCPropertyDecl
  | CXCursor_ObjCIvarDecl
  | CXCursor_ObjCInstanceMethodDecl
  | CXCursor_ObjCClassMethodDecl
  | CXCursor_ObjCImplementationDecl
  | CXCursor_ObjCCategoryImplDecl
  | CXCursor_TypedefDecl
  | CXCursor_CXXMethod
  | CXCursor_Namespace
  | CXCursor_LinkageSpec
  | CXCursor_Constructor
  | CXCursor_Destructor
  | CXCursor_ConversionFunction
  | CXCursor_TemplateTypeParameter
  | CXCursor_NonTypeTemplateParameter
  | CXCursor_TemplateTemplateParameter
  | CXCursor_FunctionTemplate
  | CXCursor_ClassTemplate
  | CXCursor_ClassTemplatePartialSpecialization
  | CXCursor_NamespaceAlias
  | CXCursor_UsingDirective
  | CXCursor_UsingDeclaration
  | CXCursor_TypeAliasDecl
  | CXCursor_ObjCSynthesizeDecl
  | CXCursor_ObjCDynamicDecl
  | CXCursor_CXXAccessSpecifier
  | CXCursor_FirstDecl
  | CXCursor_LastDecl
  | CXCursor_FirstRef
  | CXCursor_ObjCSuperClassRef
  | CXCursor_ObjCProtocolRef
  | CXCursor_ObjCClassRef
  | CXCursor_TypeRef
  | CXCursor_CXXBaseSpecifier
  | CXCursor_TemplateRef
  | CXCursor_NamespaceRef
  | CXCursor_MemberRef
  | CXCursor_LabelRef
  | CXCursor_OverloadedDeclRef
  | CXCursor_VariableRef
  | CXCursor_LastRef
  | CXCursor_FirstInvalid
  | CXCursor_InvalidFile
  | CXCursor_NoDeclFound
  | CXCursor_NotImplemented
  | CXCursor_InvalidCode
  | CXCursor_LastInvalid
  | CXCursor_FirstExpr
  | CXCursor_UnexposedExpr
  | CXCursor_DeclRefExpr
  | CXCursor_MemberRefExpr
  | CXCursor_CallExpr
  | CXCursor_ObjCMessageExpr
  | CXCursor_BlockExpr
  | CXCursor_IntegerLiteral
  | CXCursor_FloatingLiteral
  | CXCursor_ImaginaryLiteral
  | CXCursor_StringLiteral
  | CXCursor_CharacterLiteral
  | CXCursor_ParenExpr
  | CXCursor_UnaryOperator
  | CXCursor_ArraySubscriptExpr
  | CXCursor_BinaryOperator
  | CXCursor_CompoundAssignOperator
  | CXCursor_ConditionalOperator
  | CXCursor_CStyleCastExpr
  | CXCursor_CompoundLiteralExpr
  | CXCursor_InitListExpr
  | CXCursor_AddrLabelExpr
  | CXCursor_StmtExpr
  | CXCursor_GenericSelectionExpr
  | CXCursor_GNUNullExpr
  | CXCursor_CXXStaticCastExpr
  | CXCursor_CXXDynamicCastExpr
  | CXCursor_CXXReinterpretCastExpr
  | CXCursor_CXXConstCastExpr
  | CXCursor_CXXFunctionalCastExpr
  | CXCursor_CXXTypeidExpr
  | CXCursor_CXXBoolLiteralExpr
  | CXCursor_CXXNullPtrLiteralExpr
  | CXCursor_CXXThisExpr
  | CXCursor_CXXThrowExpr
  | CXCursor_CXXNewExpr
  | CXCursor_CXXDeleteExpr
  | CXCursor_UnaryExpr
  | CXCursor_ObjCStringLiteral
  | CXCursor_ObjCEncodeExpr
  | CXCursor_ObjCSelectorExpr
  | CXCursor_ObjCProtocolExpr
  | CXCursor_ObjCBridgedCastExpr
  | CXCursor_PackExpansionExpr
  | CXCursor_SizeOfPackExpr
  | CXCursor_LambdaExpr
  | CXCursor_ObjCBoolLiteralExpr
  | CXCursor_ObjCSelfExpr
  | CXCursor_OMPArraySectionExpr
  | CXCursor_ObjCAvailabilityCheckExpr
  | CXCursor_FixedPointLiteral
  | CXCursor_OMPArrayShapingExpr
  | CXCursor_OMPIteratorExpr
  | CXCursor_CXXAddrspaceCastExpr
  | CXCursor_LastExpr
  | CXCursor_FirstStmt
  | CXCursor_UnexposedStmt
  | CXCursor_LabelStmt
  | CXCursor_CompoundStmt
  | CXCursor_CaseStmt
  | CXCursor_DefaultStmt
  | CXCursor_IfStmt
  | CXCursor_SwitchStmt
  | CXCursor_WhileStmt
  | CXCursor_DoStmt
  | CXCursor_ForStmt
  | CXCursor_GotoStmt
  | CXCursor_IndirectGotoStmt
  | CXCursor_ContinueStmt
  | CXCursor_BreakStmt
  | CXCursor_ReturnStmt
  | CXCursor_GCCAsmStmt
  | CXCursor_AsmStmt
  | CXCursor_ObjCAtTryStmt
  | CXCursor_ObjCAtCatchStmt
  | CXCursor_ObjCAtFinallyStmt
  | CXCursor_ObjCAtThrowStmt
  | CXCursor_ObjCAtSynchronizedStmt
  | CXCursor_ObjCAutoreleasePoolStmt
  | CXCursor_ObjCForCollectionStmt
  | CXCursor_CXXCatchStmt
  | CXCursor_CXXTryStmt
  | CXCursor_CXXForRangeStmt
  | CXCursor_SEHTryStmt
  | CXCursor_SEHExceptStmt
  | CXCursor_SEHFinallyStmt
  | CXCursor_MSAsmStmt
  | CXCursor_NullStmt
  | CXCursor_DeclStmt
  | CXCursor_OMPParallelDirective
  | CXCursor_OMPSimdDirective
  | CXCursor_OMPForDirective
  | CXCursor_OMPSectionsDirective
  | CXCursor_OMPSectionDirective
  | CXCursor_OMPSingleDirective
  | CXCursor_OMPParallelForDirective
  | CXCursor_OMPParallelSectionsDirective
  | CXCursor_OMPTaskDirective
  | CXCursor_OMPMasterDirective
  | CXCursor_OMPCriticalDirective
  | CXCursor_OMPTaskyieldDirective
  | CXCursor_OMPBarrierDirective
  | CXCursor_OMPTaskwaitDirective
  | CXCursor_OMPFlushDirective
  | CXCursor_SEHLeaveStmt
  | CXCursor_OMPOrderedDirective
  | CXCursor_OMPAtomicDirective
  | CXCursor_OMPForSimdDirective
  | CXCursor_OMPParallelForSimdDirective
  | CXCursor_OMPTargetDirective
  | CXCursor_OMPTeamsDirective
  | CXCursor_OMPTaskgroupDirective
  | CXCursor_OMPCancellationPointDirective
  | CXCursor_OMPCancelDirective
  | CXCursor_OMPTargetDataDirective
  | CXCursor_OMPTaskLoopDirective
  | CXCursor_OMPTaskLoopSimdDirective
  | CXCursor_OMPDistributeDirective
  | CXCursor_OMPTargetEnterDataDirective
  | CXCursor_OMPTargetExitDataDirective
  | CXCursor_OMPTargetParallelDirective
  | CXCursor_OMPTargetParallelForDirective
  | CXCursor_OMPTargetUpdateDirective
  | CXCursor_OMPDistributeParallelForDirective
  | CXCursor_OMPDistributeParallelForSimdDirective
  | CXCursor_OMPDistributeSimdDirective
  | CXCursor_OMPTargetParallelForSimdDirective
  | CXCursor_OMPTargetSimdDirective
  | CXCursor_OMPTeamsDistributeDirective
  | CXCursor_OMPTeamsDistributeSimdDirective
  | CXCursor_OMPTeamsDistributeParallelForSimdDirective
  | CXCursor_OMPTeamsDistributeParallelForDirective
  | CXCursor_OMPTargetTeamsDirective
  | CXCursor_OMPTargetTeamsDistributeDirective
  | CXCursor_OMPTargetTeamsDistributeParallelForDirective
  | CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective
  | CXCursor_OMPTargetTeamsDistributeSimdDirective
  | CXCursor_BuiltinBitCastExpr
  | CXCursor_OMPMasterTaskLoopDirective
  | CXCursor_OMPParallelMasterTaskLoopDirective
  | CXCursor_OMPMasterTaskLoopSimdDirective
  | CXCursor_OMPParallelMasterTaskLoopSimdDirective
  | CXCursor_OMPParallelMasterDirective
  | CXCursor_OMPDepobjDirective
  | CXCursor_OMPScanDirective
  | CXCursor_OMPTileDirective
  | CXCursor_OMPCanonicalLoop
  | CXCursor_OMPInteropDirective
  | CXCursor_OMPDispatchDirective
  | CXCursor_OMPMaskedDirective
  | CXCursor_OMPUnrollDirective
  | CXCursor_LastStmt
  | CXCursor_TranslationUnit
  | CXCursor_FirstAttr
  | CXCursor_UnexposedAttr
  | CXCursor_IBActionAttr
  | CXCursor_IBOutletAttr
  | CXCursor_IBOutletCollectionAttr
  | CXCursor_CXXFinalAttr
  | CXCursor_CXXOverrideAttr
  | CXCursor_AnnotateAttr
  | CXCursor_AsmLabelAttr
  | CXCursor_PackedAttr
  | CXCursor_PureAttr
  | CXCursor_ConstAttr
  | CXCursor_NoDuplicateAttr
  | CXCursor_CUDAConstantAttr
  | CXCursor_CUDADeviceAttr
  | CXCursor_CUDAGlobalAttr
  | CXCursor_CUDAHostAttr
  | CXCursor_CUDASharedAttr
  | CXCursor_VisibilityAttr
  | CXCursor_DLLExport
  | CXCursor_DLLImport
  | CXCursor_NSReturnsRetained
  | CXCursor_NSReturnsNotRetained
  | CXCursor_NSReturnsAutoreleased
  | CXCursor_NSConsumesSelf
  | CXCursor_NSConsumed
  | CXCursor_ObjCException
  | CXCursor_ObjCNSObject
  | CXCursor_ObjCIndependentClass
  | CXCursor_ObjCPreciseLifetime
  | CXCursor_ObjCReturnsInnerPointer
  | CXCursor_ObjCRequiresSuper
  | CXCursor_ObjCRootClass
  | CXCursor_ObjCSubclassingRestricted
  | CXCursor_ObjCExplicitProtocolImpl
  | CXCursor_ObjCDesignatedInitializer
  | CXCursor_ObjCRuntimeVisible
  | CXCursor_ObjCBoxable
  | CXCursor_FlagEnum
  | CXCursor_ConvergentAttr
  | CXCursor_WarnUnusedAttr
  | CXCursor_WarnUnusedResultAttr
  | CXCursor_AlignedAttr
  | CXCursor_LastAttr
  | CXCursor_PreprocessingDirective
  | CXCursor_MacroDefinition
  | CXCursor_MacroExpansion
  | CXCursor_MacroInstantiation
  | CXCursor_InclusionDirective
  | CXCursor_FirstPreprocessing
  | CXCursor_LastPreprocessing
  | CXCursor_ModuleImportDecl
  | CXCursor_TypeAliasTemplateDecl
  | CXCursor_StaticAssert
  | CXCursor_FriendDecl
  | CXCursor_FirstExtraDecl
  | CXCursor_LastExtraDecl
  | CXCursor_OverloadCandidate
  deriving BEq, DecidableEq

open CXCursorKind

example (h : CXCursor_CUDAGlobalAttr = CXCursor_CUDAHostAttr) : False := by
  contradiction

#eval CXCursor_CUDAGlobalAttr == CXCursor_CUDAHostAttr

#eval decide (CXCursor_CUDAGlobalAttr = CXCursor_CUDAHostAttr)