diff --git a/example/libclang-example/generated_bindings.dart b/example/libclang-example/generated_bindings.dart index f68f6323..8f19852d 100644 --- a/example/libclang-example/generated_bindings.dart +++ b/example/libclang-example/generated_bindings.dart @@ -12,22 +12,54 @@ void init(ffi.DynamicLibrary dylib) { } /// Contains the results of code-completion. +/// +/// This data structure contains the results of code completion, as +/// produced by \c clang_codeCompleteAt(). Its contents must be freed by +/// \c clang_disposeCodeCompleteResults. class CXCodeCompleteResults extends ffi.Struct { + /// The code-completion results. ffi.Pointer Results; + /// The number of code-completion results stored in the + /// \c Results array. @ffi.Uint32() int NumResults; } /// A single result of code completion. class CXCompletionResult extends ffi.Struct { + /// The kind of entity that this completion refers to. + /// + /// The cursor kind will be a macro, keyword, or a declaration (one of the + /// *Decl cursor kinds), describing the entity that the completion is + /// referring to. + /// + /// \todo In the future, we would like to provide a full cursor, to allow + /// the client to extract additional information from declaration. @ffi.Int32() int CursorKind; + /// The code-completion string that describes how to insert this + /// code-completion result into the editing buffer. ffi.Pointer CompletionString; } -/// A cursor representing some element in the abstract syntax tree for a translation unit. +/// A cursor representing some element in the abstract syntax tree for +/// a translation unit. +/// +/// The cursor abstraction unifies the different kinds of entities in a +/// program--declaration, statements, expressions, references to declarations, +/// etc.--under a single "cursor" abstraction with a common set of operations. +/// Common operation for a cursor include: getting the physical location in +/// a source file where the cursor points, getting the name associated with a +/// cursor, and retrieving cursors for any child nodes of a particular cursor. +/// +/// Cursors can be produced in two specific ways. +/// clang_getTranslationUnitCursor() produces a cursor for a translation unit, +/// from which one can use clang_visitChildren() to explore the rest of the +/// translation unit. clang_getCursor() maps from a physical source location +/// to the entity that resides at that location, allowing one to map from the +/// source code into the AST. class CXCursor extends ffi.Struct { @ffi.Int32() int kind; @@ -110,7 +142,8 @@ typedef CXFieldVisitor = ffi.Int32 Function( ffi.Pointer, ); -/// Uniquely identifies a CXFile, that refers to the same underlying file, across an indexing session. +/// Uniquely identifies a CXFile, that refers to the same underlying file, +/// across an indexing session. class CXFileUniqueID extends ffi.Struct { @ffi.Uint64() int _data_item_0; @@ -173,9 +206,25 @@ class _ArrayHelper_CXFileUniqueID_data { } class CXGlobalOptFlags { + /// Used to indicate that no special CXIndex options are needed. static const int CXGlobalOpt_None = 0; + + /// Used to indicate that threads that libclang creates for indexing + /// purposes should use background priority. + /// + /// Affects #clang_indexSourceFile, #clang_indexTranslationUnit, + /// #clang_parseTranslationUnit, #clang_saveTranslationUnit. static const int CXGlobalOpt_ThreadBackgroundPriorityForIndexing = 1; + + /// Used to indicate that threads that libclang creates for editing + /// purposes should use background priority. + /// + /// Affects #clang_reparseTranslationUnit, #clang_codeCompleteAt, + /// #clang_annotateTokens static const int CXGlobalOpt_ThreadBackgroundPriorityForEditing = 2; + + /// Used to indicate that all threads that libclang creates should use + /// background priority. static const int CXGlobalOpt_ThreadBackgroundPriorityForAll = 3; } @@ -311,10 +360,15 @@ typedef CXInclusionVisitor = ffi.Void Function( ffi.Pointer, ); -/// Describes the availability of a given entity on a particular platform, e.g., a particular class might only be available on Mac OS 10.7 or newer. +/// Describes the availability of a given entity on a particular platform, e.g., +/// a particular class might only be available on Mac OS 10.7 or newer. class CXPlatformAvailability extends ffi.Struct {} -/// Identifies a specific source location within a translation unit. +/// Identifies a specific source location within a translation +/// unit. +/// +/// Use clang_getExpansionLocation() or clang_getSpellingLocation() +/// to map a source location to a particular file, line, and column. class CXSourceLocation extends ffi.Struct { ffi.Pointer _ptr_data_item_0; ffi.Pointer _ptr_data_item_1; @@ -376,6 +430,9 @@ class _ArrayHelper_CXSourceLocation_ptr_data { } /// Identifies a half-open character range in the source code. +/// +/// Use clang_getRangeStart() and clang_getRangeEnd() to retrieve the +/// starting and end locations from a source range, respectively. class CXSourceRange extends ffi.Struct { ffi.Pointer _ptr_data_item_0; ffi.Pointer _ptr_data_item_1; @@ -441,13 +498,20 @@ class _ArrayHelper_CXSourceRange_ptr_data { /// Identifies an array of ranges. class CXSourceRangeList extends ffi.Struct { + /// The number of ranges in the \c ranges array. @ffi.Uint32() int count; + /// An array of \c CXSourceRanges. ffi.Pointer ranges; } /// A character string. +/// +/// The \c CXString type is used to return strings from the interface when +/// the ownership of that string might differ from one call to the next. +/// Use \c clang_getCString() to retrieve the string data and, once finished +/// with the string data, call \c clang_disposeString() to free the string. class CXString extends ffi.Struct { ffi.Pointer data; @@ -610,7 +674,11 @@ class _ArrayHelper_CXType_data { /// Describes the kind of type class CXTypeKind { + /// Represents an invalid type (e.g., where no type is available). static const int CXType_Invalid = 0; + + /// A type whose specific kind is not exposed via this + /// interface. static const int CXType_Unexposed = 1; static const int CXType_Void = 2; static const int CXType_Bool = 3; @@ -670,6 +738,10 @@ class CXTypeKind { static const int CXType_DependentSizedArray = 116; static const int CXType_MemberPointer = 117; static const int CXType_Auto = 118; + + /// Represents a type that was referred to using an elaborated type keyword. + /// + /// E.g., struct S, or via a qualified name, e.g., N::M::type, or both. static const int CXType_Elaborated = 119; static const int CXType_Pipe = 120; static const int CXType_OCLImage1dRO = 121; @@ -731,43 +803,73 @@ class CXTypeKind { } /// Provides the contents of a file that has not yet been saved to disk. +/// +/// Each CXUnsavedFile instance provides the name of a file on the +/// system along with the current contents of that file that have not +/// yet been saved to disk. class CXUnsavedFile extends ffi.Struct { + /// The file whose contents have not yet been saved. + /// + /// This file must already exist in the file system. ffi.Pointer Filename; + /// A buffer containing the unsaved contents of this file. ffi.Pointer Contents; + /// The length of the unsaved contents of this buffer. @ffi.Uint64() int Length; } /// Describes a version number of the form major.minor.subminor. class CXVersion extends ffi.Struct { + /// The major version number, e.g., the '10' in '10.7.3'. A negative + /// value indicates that there is no version number at all. @ffi.Int32() int Major; + /// The minor version number, e.g., the '7' in '10.7.3'. This value + /// will be negative if no minor version number was provided, e.g., for + /// version '10'. @ffi.Int32() int Minor; + /// The subminor version number, e.g., the '3' in '10.7.3'. This value + /// will be negative if no minor or subminor version number was provided, + /// e.g., in version '10' or '10.7'. @ffi.Int32() int Subminor; } -/// A group of callbacks used by #clang_indexSourceFile and #clang_indexTranslationUnit. +/// A group of callbacks used by #clang_indexSourceFile and +/// #clang_indexTranslationUnit. class IndexerCallbacks extends ffi.Struct { + /// Called periodically to check whether indexing should be aborted. + /// Should return 0 to continue, and non-zero to abort. ffi.Pointer> abortQuery; + /// Called at the end of indexing; passes the complete diagnostic set. ffi.Pointer> diagnostic; ffi.Pointer> enteredMainFile; + /// Called when a file gets \#included/\#imported. ffi.Pointer> ppIncludedFile; + /// Called when a AST file (PCH or module) gets imported. + /// + /// AST files will not get indexed (there will not be callbacks to index all + /// the entities in an AST file). The recommended action is that, if the AST + /// file is not already indexed, to initiate a new indexing job specific to + /// the AST file. ffi.Pointer> importedASTFile; + /// Called at the beginning of indexing a translation unit. ffi.Pointer> startedTranslationUnit; ffi.Pointer> indexDeclaration; + /// Called to index a reference of an entity. ffi.Pointer> indexEntityReference; } @@ -830,6 +932,9 @@ typedef _typedefC_noname_9 = ffi.Void Function( ); /// Gets the general options associated with a CXIndex. +/// +/// \returns A bitmask of options, a bitwise OR of CXGlobalOpt_XXX flags that +/// are associated with the given CXIndex object. int clang_CXIndex_getGlobalOptions( ffi.Pointer arg0, ) { @@ -851,6 +956,16 @@ typedef _dart_clang_CXIndex_getGlobalOptions = int Function( ); /// Sets general options associated with a CXIndex. +/// +/// For example: +/// \code +/// CXIndex idx = ...; +/// clang_CXIndex_setGlobalOptions(idx, +/// clang_CXIndex_getGlobalOptions(idx) | +/// CXGlobalOpt_ThreadBackgroundPriorityForIndexing); +/// \endcode +/// +/// \param options A bitmask of options, a bitwise OR of CXGlobalOpt_XXX flags. void clang_CXIndex_setGlobalOptions( ffi.Pointer arg0, int options, @@ -876,6 +991,10 @@ typedef _dart_clang_CXIndex_setGlobalOptions = void Function( ); /// Sets the invocation emission path option in a CXIndex. +/// +/// The invocation emission path specifies a path which will contain log +/// files for certain libclang invocations. A null value (default) implies that +/// libclang invocations are not logged.. void clang_CXIndex_setInvocationEmissionPathOption( ffi.Pointer arg0, ffi.Pointer Path, @@ -951,6 +1070,31 @@ typedef _dart_clang_Cursor_getBriefCommentText_wrap = ffi.Pointer ffi.Pointer cursor, ); +/// Returns the comment range. +ffi.Pointer clang_Cursor_getCommentRange_wrap( + ffi.Pointer cursor, +) { + return _clang_Cursor_getCommentRange_wrap( + cursor, + ); +} + +final _dart_clang_Cursor_getCommentRange_wrap + _clang_Cursor_getCommentRange_wrap = _dylib.lookupFunction< + _c_clang_Cursor_getCommentRange_wrap, + _dart_clang_Cursor_getCommentRange_wrap>( + 'clang_Cursor_getCommentRange_wrap'); + +typedef _c_clang_Cursor_getCommentRange_wrap = ffi.Pointer + Function( + ffi.Pointer cursor, +); + +typedef _dart_clang_Cursor_getCommentRange_wrap = ffi.Pointer + Function( + ffi.Pointer cursor, +); + int clang_Cursor_getNumArguments_wrap( ffi.Pointer cursor, ) { @@ -973,6 +1117,30 @@ typedef _dart_clang_Cursor_getNumArguments_wrap = int Function( ffi.Pointer cursor, ); +/// Returns the raw comment. +ffi.Pointer clang_Cursor_getRawCommentText_wrap( + ffi.Pointer cursor, +) { + return _clang_Cursor_getRawCommentText_wrap( + cursor, + ); +} + +final _dart_clang_Cursor_getRawCommentText_wrap + _clang_Cursor_getRawCommentText_wrap = _dylib.lookupFunction< + _c_clang_Cursor_getRawCommentText_wrap, + _dart_clang_Cursor_getRawCommentText_wrap>( + 'clang_Cursor_getRawCommentText_wrap'); + +typedef _c_clang_Cursor_getRawCommentText_wrap = ffi.Pointer Function( + ffi.Pointer cursor, +); + +typedef _dart_clang_Cursor_getRawCommentText_wrap = ffi.Pointer + Function( + ffi.Pointer cursor, +); + /// Disposes the created Eval memory. void clang_EvalResult_dispose( ffi.Pointer E, @@ -994,7 +1162,8 @@ typedef _dart_clang_EvalResult_dispose = void Function( ffi.Pointer E, ); -/// Returns the evaluation result as double if the kind is double. +/// Returns the evaluation result as double if the +/// kind is double. double clang_EvalResult_getAsDouble( ffi.Pointer E, ) { @@ -1015,7 +1184,8 @@ typedef _dart_clang_EvalResult_getAsDouble = double Function( ffi.Pointer E, ); -/// Returns the evaluation result as integer if the kind is Int. +/// Returns the evaluation result as integer if the +/// kind is Int. int clang_EvalResult_getAsInt( ffi.Pointer E, ) { @@ -1036,7 +1206,9 @@ typedef _dart_clang_EvalResult_getAsInt = int Function( ffi.Pointer E, ); -/// Returns the evaluation result as a long long integer if the kind is Int. This prevents overflows that may happen if the result is returned with clang_EvalResult_getAsInt. +/// Returns the evaluation result as a long long integer if the +/// kind is Int. This prevents overflows that may happen if the result is +/// returned with clang_EvalResult_getAsInt. int clang_EvalResult_getAsLongLong( ffi.Pointer E, ) { @@ -1057,7 +1229,10 @@ typedef _dart_clang_EvalResult_getAsLongLong = int Function( ffi.Pointer E, ); -/// Returns the evaluation result as a constant string if the kind is other than Int or float. User must not free this pointer, instead call clang_EvalResult_dispose on the CXEvalResult returned by clang_Cursor_Evaluate. +/// Returns the evaluation result as a constant string if the +/// kind is other than Int or float. User must not free this pointer, +/// instead call clang_EvalResult_dispose on the CXEvalResult returned +/// by clang_Cursor_Evaluate. ffi.Pointer clang_EvalResult_getAsStr( ffi.Pointer E, ) { @@ -1078,7 +1253,8 @@ typedef _dart_clang_EvalResult_getAsStr = ffi.Pointer Function( ffi.Pointer E, ); -/// Returns the evaluation result as an unsigned integer if the kind is Int and clang_EvalResult_isUnsignedInt is non-zero. +/// Returns the evaluation result as an unsigned integer if +/// the kind is Int and clang_EvalResult_isUnsignedInt is non-zero. int clang_EvalResult_getAsUnsigned( ffi.Pointer E, ) { @@ -1120,7 +1296,8 @@ typedef _dart_clang_EvalResult_getKind = int Function( ffi.Pointer E, ); -/// Returns a non-zero value if the kind is Int and the evaluation result resulted in an unsigned integer. +/// Returns a non-zero value if the kind is Int and the evaluation +/// result resulted in an unsigned integer. int clang_EvalResult_isUnsignedInt( ffi.Pointer E, ) { @@ -1141,7 +1318,8 @@ typedef _dart_clang_EvalResult_isUnsignedInt = int Function( ffi.Pointer E, ); -/// Returns non-zero if the file1 and file2 point to the same file, or they are both NULL. +/// Returns non-zero if the \c file1 and \c file2 point to the same file, +/// or they are both NULL. int clang_File_isEqual( ffi.Pointer file1, ffi.Pointer file2, @@ -1166,7 +1344,10 @@ typedef _dart_clang_File_isEqual = int Function( ffi.Pointer file2, ); -/// An indexing action/session, to be applied to one or multiple translation units. +/// An indexing action/session, to be applied to one or multiple +/// translation units. +/// +/// \param CIdx The index object with which the index action will be associated. ffi.Pointer clang_IndexAction_create( ffi.Pointer CIdx, ) { @@ -1188,6 +1369,9 @@ typedef _dart_clang_IndexAction_create = ffi.Pointer Function( ); /// Destroy the given index action. +/// +/// The index action must not be destroyed until all of the translation units +/// created within that index action have been destroyed. void clang_IndexAction_dispose( ffi.Pointer arg0, ) { @@ -1208,7 +1392,9 @@ typedef _dart_clang_IndexAction_dispose = void Function( ffi.Pointer arg0, ); -/// Returns the module file where the provided module object came from. +/// \param Module a module object. +/// +/// \returns the module file where the provided module object came from. ffi.Pointer clang_Module_getASTFile( ffi.Pointer Module, ) { @@ -1229,7 +1415,9 @@ typedef _dart_clang_Module_getASTFile = ffi.Pointer Function( ffi.Pointer Module, ); -/// Returns the number of top level headers associated with this module. +/// \param Module a module object. +/// +/// \returns the number of top level headers associated with this module. int clang_Module_getNumTopLevelHeaders( ffi.Pointer arg0, ffi.Pointer Module, @@ -1256,7 +1444,10 @@ typedef _dart_clang_Module_getNumTopLevelHeaders = int Function( ffi.Pointer Module, ); -/// Returns the parent of a sub-module or NULL if the given module is top-level, e.g. for 'std.vector' it will return the 'std' module. +/// \param Module a module object. +/// +/// \returns the parent of a sub-module or NULL if the given module is top-level, +/// e.g. for 'std.vector' it will return the 'std' module. ffi.Pointer clang_Module_getParent( ffi.Pointer Module, ) { @@ -1277,7 +1468,11 @@ typedef _dart_clang_Module_getParent = ffi.Pointer Function( ffi.Pointer Module, ); -/// Returns the specified top level header associated with the module. +/// \param Module a module object. +/// +/// \param Index top level header index (zero-based). +/// +/// \returns the specified top level header associated with the module. ffi.Pointer clang_Module_getTopLevelHeader( ffi.Pointer arg0, ffi.Pointer Module, @@ -1306,7 +1501,9 @@ typedef _dart_clang_Module_getTopLevelHeader = ffi.Pointer Function( int Index, ); -/// Returns non-zero if the module is a system one. +/// \param Module a module object. +/// +/// \returns non-zero if the module is a system one. int clang_Module_isSystem( ffi.Pointer Module, ) { @@ -1426,6 +1623,8 @@ typedef _dart_clang_TargetInfo_dispose = void Function( ); /// Get the pointer width of the target in bits. +/// +/// Returns -1 in case of error. int clang_TargetInfo_getPointerWidth( ffi.Pointer Info, ) { @@ -1467,7 +1666,34 @@ typedef _dart_clang_Type_getNamedType_wrap = ffi.Pointer Function( ffi.Pointer elaboratedType, ); -/// Annotate the given set of tokens by providing cursors for each token that can be mapped to a specific entity within the abstract syntax tree. +/// Annotate the given set of tokens by providing cursors for each token +/// that can be mapped to a specific entity within the abstract syntax tree. +/// +/// This token-annotation routine is equivalent to invoking +/// clang_getCursor() for the source locations of each of the +/// tokens. The cursors provided are filtered, so that only those +/// cursors that have a direct correspondence to the token are +/// accepted. For example, given a function call \c f(x), +/// clang_getCursor() would provide the following cursors: +/// +/// * when the cursor is over the 'f', a DeclRefExpr cursor referring to 'f'. +/// * when the cursor is over the '(' or the ')', a CallExpr referring to 'f'. +/// * when the cursor is over the 'x', a DeclRefExpr cursor referring to 'x'. +/// +/// Only the first and last of these cursors will occur within the +/// annotate, since the tokens "f" and "x' directly refer to a function +/// and a variable, respectively, but the parentheses are just a small +/// part of the full syntax of the function call expression, which is +/// not provided as an annotation. +/// +/// \param TU the translation unit that owns the given tokens. +/// +/// \param Tokens the set of tokens to annotate. +/// +/// \param NumTokens the number of tokens in \p Tokens. +/// +/// \param Cursors an array of \p NumTokens cursors, whose contents will be +/// replaced with the cursors corresponding to each token. void clang_annotateTokens( ffi.Pointer TU, ffi.Pointer Tokens, @@ -1501,6 +1727,71 @@ typedef _dart_clang_annotateTokens = void Function( ); /// Perform code completion at a given location in a translation unit. +/// +/// This function performs code completion at a particular file, line, and +/// column within source code, providing results that suggest potential +/// code snippets based on the context of the completion. The basic model +/// for code completion is that Clang will parse a complete source file, +/// performing syntax checking up to the location where code-completion has +/// been requested. At that point, a special code-completion token is passed +/// to the parser, which recognizes this token and determines, based on the +/// current location in the C/Objective-C/C++ grammar and the state of +/// semantic analysis, what completions to provide. These completions are +/// returned via a new \c CXCodeCompleteResults structure. +/// +/// Code completion itself is meant to be triggered by the client when the +/// user types punctuation characters or whitespace, at which point the +/// code-completion location will coincide with the cursor. For example, if \c p +/// is a pointer, code-completion might be triggered after the "-" and then +/// after the ">" in \c p->. When the code-completion location is after the ">", +/// the completion results will provide, e.g., the members of the struct that +/// "p" points to. The client is responsible for placing the cursor at the +/// beginning of the token currently being typed, then filtering the results +/// based on the contents of the token. For example, when code-completing for +/// the expression \c p->get, the client should provide the location just after +/// the ">" (e.g., pointing at the "g") to this code-completion hook. Then, the +/// client can filter the results based on the current token text ("get"), only +/// showing those results that start with "get". The intent of this interface +/// is to separate the relatively high-latency acquisition of code-completion +/// results from the filtering of results on a per-character basis, which must +/// have a lower latency. +/// +/// \param TU The translation unit in which code-completion should +/// occur. The source files for this translation unit need not be +/// completely up-to-date (and the contents of those source files may +/// be overridden via \p unsaved_files). Cursors referring into the +/// translation unit may be invalidated by this invocation. +/// +/// \param complete_filename The name of the source file where code +/// completion should be performed. This filename may be any file +/// included in the translation unit. +/// +/// \param complete_line The line at which code-completion should occur. +/// +/// \param complete_column The column at which code-completion should occur. +/// Note that the column should point just after the syntactic construct that +/// initiated code completion, and not in the middle of a lexical token. +/// +/// \param unsaved_files the Files that have not yet been saved to disk +/// but may be required for parsing or code completion, including the +/// contents of those files. The contents and name of these files (as +/// specified by CXUnsavedFile) are copied when necessary, so the +/// client only needs to guarantee their validity until the call to +/// this function returns. +/// +/// \param num_unsaved_files The number of unsaved file entries in \p +/// unsaved_files. +/// +/// \param options Extra options that control the behavior of code +/// completion, expressed as a bitwise OR of the enumerators of the +/// CXCodeComplete_Flags enumeration. The +/// \c clang_defaultCodeCompleteOptions() function returns a default set +/// of code-completion options. +/// +/// \returns If successful, a new \c CXCodeCompleteResults structure +/// containing code-completion results, which should eventually be +/// freed with \c clang_disposeCodeCompleteResults(). If code +/// completion fails, returns NULL. ffi.Pointer clang_codeCompleteAt( ffi.Pointer TU, ffi.Pointer complete_filename, @@ -1546,7 +1837,20 @@ typedef _dart_clang_codeCompleteAt = ffi.Pointer int options, ); -/// Returns the cursor kind for the container for the current code completion context. The container is only guaranteed to be set for contexts where a container exists (i.e. member accesses or Objective-C message sends); if there is not a container, this function will return CXCursor_InvalidCode. +/// Returns the cursor kind for the container for the current code +/// completion context. The container is only guaranteed to be set for +/// contexts where a container exists (i.e. member accesses or Objective-C +/// message sends); if there is not a container, this function will return +/// CXCursor_InvalidCode. +/// +/// \param Results the code completion results to query +/// +/// \param IsIncomplete on return, this value will be false if Clang has complete +/// information about the container. If Clang does not have complete +/// information, this value will be true. +/// +/// \returns the container kind, or CXCursor_InvalidCode if there is not a +/// container int clang_codeCompleteGetContainerKind( ffi.Pointer Results, ffi.Pointer IsIncomplete, @@ -1573,7 +1877,13 @@ typedef _dart_clang_codeCompleteGetContainerKind = int Function( ffi.Pointer IsIncomplete, ); -/// Determines what completions are appropriate for the context the given code completion. +/// Determines what completions are appropriate for the context +/// the given code completion. +/// +/// \param Results the code completion results to query +/// +/// \returns the kinds of completions that are appropriate for use +/// along with the given code completion results. int clang_codeCompleteGetContexts( ffi.Pointer Results, ) { @@ -1595,6 +1905,12 @@ typedef _dart_clang_codeCompleteGetContexts = int Function( ); /// Retrieve a diagnostic associated with the given code completion. +/// +/// \param Results the code completion results to query. +/// \param Index the zero-based diagnostic number to retrieve. +/// +/// \returns the requested diagnostic. This diagnostic must be freed +/// via a call to \c clang_disposeDiagnostic(). ffi.Pointer clang_codeCompleteGetDiagnostic( ffi.Pointer Results, int Index, @@ -1620,7 +1936,8 @@ typedef _dart_clang_codeCompleteGetDiagnostic = ffi.Pointer Function( int Index, ); -/// Determine the number of diagnostics produced prior to the location where code completion was performed. +/// Determine the number of diagnostics produced prior to the +/// location where code completion was performed. int clang_codeCompleteGetNumDiagnostics( ffi.Pointer Results, ) { @@ -1657,6 +1974,43 @@ typedef _c_clang_createCXCursorSet = ffi.Pointer Function(); typedef _dart_clang_createCXCursorSet = ffi.Pointer Function(); /// Provides a shared context for creating translation units. +/// +/// It provides two options: +/// +/// - excludeDeclarationsFromPCH: When non-zero, allows enumeration of "local" +/// declarations (when loading any new translation units). A "local" declaration +/// is one that belongs in the translation unit itself and not in a precompiled +/// header that was used by the translation unit. If zero, all declarations +/// will be enumerated. +/// +/// Here is an example: +/// +/// \code +/// // excludeDeclsFromPCH = 1, displayDiagnostics=1 +/// Idx = clang_createIndex(1, 1); +/// +/// // IndexTest.pch was produced with the following command: +/// // "clang -x c IndexTest.h -emit-ast -o IndexTest.pch" +/// TU = clang_createTranslationUnit(Idx, "IndexTest.pch"); +/// +/// // This will load all the symbols from 'IndexTest.pch' +/// clang_visitChildren(clang_getTranslationUnitCursor(TU), +/// TranslationUnitVisitor, 0); +/// clang_disposeTranslationUnit(TU); +/// +/// // This will load all the symbols from 'IndexTest.c', excluding symbols +/// // from 'IndexTest.pch'. +/// char *args[] = { "-Xclang", "-include-pch=IndexTest.pch" }; +/// TU = clang_createTranslationUnitFromSourceFile(Idx, "IndexTest.c", 2, args, +/// 0, 0); +/// clang_visitChildren(clang_getTranslationUnitCursor(TU), +/// TranslationUnitVisitor, 0); +/// clang_disposeTranslationUnit(TU); +/// \endcode +/// +/// This process of creating the 'pch', loading it separately, and using it (via +/// -include-pch) allows 'excludeDeclsFromPCH' to remove redundant callbacks +/// (which gives the indexer the same performance benefit as the compiler). ffi.Pointer clang_createIndex( int excludeDeclarationsFromPCH, int displayDiagnostics, @@ -1681,7 +2035,10 @@ typedef _dart_clang_createIndex = ffi.Pointer Function( int displayDiagnostics, ); -/// Same as clang_createTranslationUnit2, but returns the CXTranslationUnit instead of an error code. In case of an error this routine returns a NULL CXTranslationUnit, without further detailed error codes. +/// Same as \c clang_createTranslationUnit2, but returns +/// the \c CXTranslationUnit instead of an error code. In case of an error this +/// routine returns a \c NULL \c CXTranslationUnit, without further detailed +/// error codes. ffi.Pointer clang_createTranslationUnit( ffi.Pointer CIdx, ffi.Pointer ast_filename, @@ -1708,7 +2065,12 @@ typedef _dart_clang_createTranslationUnit = ffi.Pointer ffi.Pointer ast_filename, ); -/// Create a translation unit from an AST file ( -emit-ast). +/// Create a translation unit from an AST file (\c -emit-ast). +/// +/// \param[out] out_TU A non-NULL pointer to store the created +/// \c CXTranslationUnit. +/// +/// \returns Zero on success, otherwise returns an error code. int clang_createTranslationUnit2( ffi.Pointer CIdx, ffi.Pointer ast_filename, @@ -1737,7 +2099,44 @@ typedef _dart_clang_createTranslationUnit2 = int Function( ffi.Pointer> out_TU, ); -/// Return the CXTranslationUnit for a given source file and the provided command line arguments one would pass to the compiler. +/// Return the CXTranslationUnit for a given source file and the provided +/// command line arguments one would pass to the compiler. +/// +/// Note: The 'source_filename' argument is optional. If the caller provides a +/// NULL pointer, the name of the source file is expected to reside in the +/// specified command line arguments. +/// +/// Note: When encountered in 'clang_command_line_args', the following options +/// are ignored: +/// +/// '-c' +/// '-emit-ast' +/// '-fsyntax-only' +/// '-o \' (both '-o' and '\' are ignored) +/// +/// \param CIdx The index object with which the translation unit will be +/// associated. +/// +/// \param source_filename The name of the source file to load, or NULL if the +/// source file is included in \p clang_command_line_args. +/// +/// \param num_clang_command_line_args The number of command-line arguments in +/// \p clang_command_line_args. +/// +/// \param clang_command_line_args The command-line arguments that would be +/// passed to the \c clang executable if it were being invoked out-of-process. +/// These command-line options will be parsed and will affect how the translation +/// unit is parsed. Note that the following options are ignored: '-c', +/// '-emit-ast', '-fsyntax-only' (which is the default), and '-o \'. +/// +/// \param num_unsaved_files the number of unsaved file entries in \p +/// unsaved_files. +/// +/// \param unsaved_files the files that have not yet been saved to disk +/// but may be required for code completion, including the contents of +/// those files. The contents and name of these files (as specified by +/// CXUnsavedFile) are copied when necessary, so the client only needs to +/// guarantee their validity until the call to this function returns. ffi.Pointer clang_createTranslationUnitFromSourceFile( ffi.Pointer CIdx, ffi.Pointer source_filename, @@ -1782,7 +2181,8 @@ typedef _dart_clang_createTranslationUnitFromSourceFile ffi.Pointer unsaved_files, ); -/// Returns a default set of code-completion options that can be passed to clang_codeCompleteAt(). +/// Returns a default set of code-completion options that can be +/// passed to\c clang_codeCompleteAt(). int clang_defaultCodeCompleteOptions() { return _clang_defaultCodeCompleteOptions(); } @@ -1796,7 +2196,11 @@ typedef _c_clang_defaultCodeCompleteOptions = ffi.Uint32 Function(); typedef _dart_clang_defaultCodeCompleteOptions = int Function(); -/// Retrieve the set of display options most similar to the default behavior of the clang compiler. +/// Retrieve the set of display options most similar to the +/// default behavior of the clang compiler. +/// +/// \returns A set of display options suitable for use with \c +/// clang_formatDiagnostic(). int clang_defaultDiagnosticDisplayOptions() { return _clang_defaultDiagnosticDisplayOptions(); } @@ -1811,7 +2215,16 @@ typedef _c_clang_defaultDiagnosticDisplayOptions = ffi.Uint32 Function(); typedef _dart_clang_defaultDiagnosticDisplayOptions = int Function(); -/// Returns the set of flags that is suitable for parsing a translation unit that is being edited. +/// Returns the set of flags that is suitable for parsing a translation +/// unit that is being edited. +/// +/// The set of flags returned provide options for \c clang_parseTranslationUnit() +/// to indicate that the translation unit is likely to be reparsed many times, +/// either explicitly (via \c clang_reparseTranslationUnit()) or implicitly +/// (e.g., by code completion (\c clang_codeCompletionAt())). The returned flag +/// set contains an unspecified set of optimizations (e.g., the precompiled +/// preamble) geared toward improving the performance of these routines. The +/// set of optimizations enabled may change from one version to the next. int clang_defaultEditingTranslationUnitOptions() { return _clang_defaultEditingTranslationUnitOptions(); } @@ -1826,7 +2239,14 @@ typedef _c_clang_defaultEditingTranslationUnitOptions = ffi.Uint32 Function(); typedef _dart_clang_defaultEditingTranslationUnitOptions = int Function(); -/// Returns the set of flags that is suitable for reparsing a translation unit. +/// Returns the set of flags that is suitable for reparsing a translation +/// unit. +/// +/// The set of flags returned provide options for +/// \c clang_reparseTranslationUnit() by default. The returned flag +/// set contains an unspecified set of optimizations geared toward common uses +/// of reparsing. The set of optimizations enabled may change from one version +/// to the next. int clang_defaultReparseOptions( ffi.Pointer TU, ) { @@ -1847,7 +2267,13 @@ typedef _dart_clang_defaultReparseOptions = int Function( ffi.Pointer TU, ); -/// Returns the set of flags that is suitable for saving a translation unit. +/// Returns the set of flags that is suitable for saving a translation +/// unit. +/// +/// The set of flags returned provide options for +/// \c clang_saveTranslationUnit() by default. The returned flag +/// set contains an unspecified set of options that save translation units with +/// the most commonly-requested data. int clang_defaultSaveOptions( ffi.Pointer TU, ) { @@ -1889,7 +2315,7 @@ typedef _dart_clang_disposeCXCursorSet = void Function( ffi.Pointer cset, ); -/// Free the memory associated with a CXPlatformAvailability structure. +/// Free the memory associated with a \c CXPlatformAvailability structure. void clang_disposeCXPlatformAvailability( ffi.Pointer availability, ) { @@ -1977,6 +2403,9 @@ typedef _dart_clang_disposeDiagnosticSet = void Function( ); /// Destroy the given index. +/// +/// The index must not be destroyed until all of the translation units created +/// within that index have been destroyed. void clang_disposeIndex( ffi.Pointer index, ) { @@ -1997,7 +2426,8 @@ typedef _dart_clang_disposeIndex = void Function( ffi.Pointer index, ); -/// Free the set of overridden cursors returned by clang_getOverriddenCursors(). +/// Free the set of overridden cursors returned by \c +/// clang_getOverriddenCursors(). void clang_disposeOverriddenCursors( ffi.Pointer overridden, ) { @@ -2018,7 +2448,7 @@ typedef _dart_clang_disposeOverriddenCursors = void Function( ffi.Pointer overridden, ); -/// Destroy the given CXSourceRangeList. +/// Destroy the given \c CXSourceRangeList. void clang_disposeSourceRangeList( ffi.Pointer ranges, ) { @@ -2142,6 +2572,30 @@ typedef _c_clang_enableStackTraces = ffi.Void Function(); typedef _dart_clang_enableStackTraces = void Function(); +int clang_equalRanges_wrap( + ffi.Pointer c1, + ffi.Pointer c2, +) { + return _clang_equalRanges_wrap( + c1, + c2, + ); +} + +final _dart_clang_equalRanges_wrap _clang_equalRanges_wrap = _dylib + .lookupFunction<_c_clang_equalRanges_wrap, _dart_clang_equalRanges_wrap>( + 'clang_equalRanges_wrap'); + +typedef _c_clang_equalRanges_wrap = ffi.Uint32 Function( + ffi.Pointer c1, + ffi.Pointer c2, +); + +typedef _dart_clang_equalRanges_wrap = int Function( + ffi.Pointer c1, + ffi.Pointer c2, +); + void clang_executeOnThread( ffi.Pointer> fn, ffi.Pointer user_data, @@ -2194,7 +2648,11 @@ typedef _dart_clang_formatDiagnostic_wrap = ffi.Pointer Function( int opts, ); -/// Retrieve all ranges from all files that were skipped by the preprocessor. +/// Retrieve all ranges from all files that were skipped by the +/// preprocessor. +/// +/// The preprocessor will skip lines when they are surrounded by an +/// if/ifdef/ifndef directive whose condition does not evaluate to true. ffi.Pointer clang_getAllSkippedRanges( ffi.Pointer tu, ) { @@ -2301,6 +2759,9 @@ typedef _dart_clang_getCanonicalType_wrap = ffi.Pointer Function( ); /// Retrieve the child diagnostics of a CXDiagnostic. +/// +/// This CXDiagnosticSet does not need to be released by +/// clang_disposeDiagnosticSet. ffi.Pointer clang_getChildDiagnostics( ffi.Pointer D, ) { @@ -2321,7 +2782,12 @@ typedef _dart_clang_getChildDiagnostics = ffi.Pointer Function( ffi.Pointer D, ); -/// Determine the availability of the entity that this code-completion string refers to. +/// Determine the availability of the entity that this code-completion +/// string refers to. +/// +/// \param completion_string The completion string to query. +/// +/// \returns The availability of the completion string. int clang_getCompletionAvailability( ffi.Pointer completion_string, ) { @@ -2343,7 +2809,15 @@ typedef _dart_clang_getCompletionAvailability = int Function( ffi.Pointer completion_string, ); -/// Retrieve the completion string associated with a particular chunk within a completion string. +/// Retrieve the completion string associated with a particular chunk +/// within a completion string. +/// +/// \param completion_string the completion string to query. +/// +/// \param chunk_number the 0-based index of the chunk in the completion string. +/// +/// \returns the completion string associated with the chunk at index +/// \c chunk_number. ffi.Pointer clang_getCompletionChunkCompletionString( ffi.Pointer completion_string, int chunk_number, @@ -2373,6 +2847,12 @@ typedef _dart_clang_getCompletionChunkCompletionString = ffi.Pointer ); /// Determine the kind of a particular chunk within a completion string. +/// +/// \param completion_string the completion string to query. +/// +/// \param chunk_number the 0-based index of the chunk in the completion string. +/// +/// \returns the kind of the chunk at the index \c chunk_number. int clang_getCompletionChunkKind( ffi.Pointer completion_string, int chunk_number, @@ -2397,7 +2877,13 @@ typedef _dart_clang_getCompletionChunkKind = int Function( int chunk_number, ); -/// Retrieve the number of annotations associated with the given completion string. +/// Retrieve the number of annotations associated with the given +/// completion string. +/// +/// \param completion_string the completion string to query. +/// +/// \returns the number of annotations associated with the given completion +/// string. int clang_getCompletionNumAnnotations( ffi.Pointer completion_string, ) { @@ -2421,6 +2907,16 @@ typedef _dart_clang_getCompletionNumAnnotations = int Function( ); /// Retrieve the number of fix-its for the given completion index. +/// +/// Calling this makes sense only if CXCodeComplete_IncludeCompletionsWithFixIts +/// option was set. +/// +/// \param results The structure keeping all completion results +/// +/// \param completion_index The index of the completion +/// +/// \return The number of fix-its which must be applied before the completion at +/// completion_index can be applied int clang_getCompletionNumFixIts( ffi.Pointer results, int completion_index, @@ -2446,6 +2942,15 @@ typedef _dart_clang_getCompletionNumFixIts = int Function( ); /// Determine the priority of this code completion. +/// +/// The priority of a code completion indicates how likely it is that this +/// particular completion is the completion that the user will select. The +/// priority is selected by various internal heuristics. +/// +/// \param completion_string The completion string to query. +/// +/// \returns The priority of this completion string. Smaller values indicate +/// higher-priority (more likely) completions. int clang_getCompletionPriority( ffi.Pointer completion_string, ) { @@ -2571,6 +3076,12 @@ typedef _dart_clang_getCursorType_wrap = ffi.Pointer Function( ); /// Retrieve a diagnostic associated with the given translation unit. +/// +/// \param Unit the translation unit to query. +/// \param Index the zero-based diagnostic number to retrieve. +/// +/// \returns the requested diagnostic. This diagnostic must be freed +/// via a call to \c clang_disposeDiagnostic(). ffi.Pointer clang_getDiagnostic( ffi.Pointer Unit, int Index, @@ -2596,6 +3107,13 @@ typedef _dart_clang_getDiagnostic = ffi.Pointer Function( ); /// Retrieve the category number for this diagnostic. +/// +/// Diagnostics can be categorized into groups along with other, related +/// diagnostics (e.g., diagnostics under the same warning flag). This routine +/// retrieves the category number for the given diagnostic. +/// +/// \returns The number of the category that contains this diagnostic, or zero +/// if this diagnostic is uncategorized. int clang_getDiagnosticCategory( ffi.Pointer arg0, ) { @@ -2617,6 +3135,12 @@ typedef _dart_clang_getDiagnosticCategory = int Function( ); /// Retrieve a diagnostic associated with the given CXDiagnosticSet. +/// +/// \param Diags the CXDiagnosticSet to query. +/// \param Index the zero-based diagnostic number to retrieve. +/// +/// \returns the requested diagnostic. This diagnostic must be freed +/// via a call to \c clang_disposeDiagnostic(). ffi.Pointer clang_getDiagnosticInSet( ffi.Pointer Diags, int Index, @@ -2641,7 +3165,8 @@ typedef _dart_clang_getDiagnosticInSet = ffi.Pointer Function( int Index, ); -/// Determine the number of fix-it hints associated with the given diagnostic. +/// Determine the number of fix-it hints associated with the +/// given diagnostic. int clang_getDiagnosticNumFixIts( ffi.Pointer Diagnostic, ) { @@ -2662,7 +3187,8 @@ typedef _dart_clang_getDiagnosticNumFixIts = int Function( ffi.Pointer Diagnostic, ); -/// Determine the number of source ranges associated with the given diagnostic. +/// Determine the number of source ranges associated with the given +/// diagnostic. int clang_getDiagnosticNumRanges( ffi.Pointer arg0, ) { @@ -2683,7 +3209,10 @@ typedef _dart_clang_getDiagnosticNumRanges = int Function( ffi.Pointer arg0, ); -/// Retrieve the complete set of diagnostics associated with a translation unit. +/// Retrieve the complete set of diagnostics associated with a +/// translation unit. +/// +/// \param Unit the translation unit to query. ffi.Pointer clang_getDiagnosticSetFromTU( ffi.Pointer Unit, ) { @@ -2748,6 +3277,13 @@ typedef _dart_clang_getEnumConstantDeclValue_wrap = int Function( ); /// Retrieve a file handle within the given translation unit. +/// +/// \param tu the translation unit +/// +/// \param file_name the name of the file. +/// +/// \returns the file handle for the named file in the translation unit \p tu, +/// or a NULL file handle if the file was not a part of this translation unit. ffi.Pointer clang_getFile( ffi.Pointer tu, ffi.Pointer file_name, @@ -2772,6 +3308,15 @@ typedef _dart_clang_getFile = ffi.Pointer Function( ); /// Retrieve the buffer associated with the given file. +/// +/// \param tu the translation unit +/// +/// \param file the file for which to retrieve the buffer. +/// +/// \param size [out] if non-NULL, will be set to the size of the buffer. +/// +/// \returns a pointer to the buffer in memory that holds the contents of +/// \p file, or a NULL pointer when the file is not loaded. ffi.Pointer clang_getFileContents( ffi.Pointer tu, ffi.Pointer file, @@ -2877,7 +3422,12 @@ typedef _dart_clang_getFileTime = int Function( ffi.Pointer SFile, ); -/// Retrieve the unique ID for the given file. +/// Retrieve the unique ID for the given \c file. +/// +/// \param file the file to get the ID for. +/// \param outID stores the returned CXFileUniqueID. +/// \returns If there was a failure getting the unique ID, returns non-zero, +/// otherwise returns 0. int clang_getFileUniqueID( ffi.Pointer file, ffi.Pointer outID, @@ -2902,7 +3452,10 @@ typedef _dart_clang_getFileUniqueID = int Function( ffi.Pointer outID, ); -/// Visit the set of preprocessor inclusions in a translation unit. The visitor function is called with the provided data for every included file. This does not include headers included by the PCH file (unless one is inspecting the inclusions in the PCH file itself). +/// Visit the set of preprocessor inclusions in a translation unit. +/// The visitor function is called with the provided data for every included +/// file. This does not include headers included by the PCH file (unless one +/// is inspecting the inclusions in the PCH file itself). void clang_getInclusions( ffi.Pointer tu, ffi.Pointer> visitor, @@ -2931,7 +3484,8 @@ typedef _dart_clang_getInclusions = void Function( ffi.Pointer client_data, ); -/// Given a CXFile header file, return the module that contains it, if one exists. +/// Given a CXFile header file, return the module that contains it, if one +/// exists. ffi.Pointer clang_getModuleForFile( ffi.Pointer arg0, ffi.Pointer arg1, @@ -2997,7 +3551,8 @@ typedef _dart_clang_getNumCompletionChunks = int Function( ffi.Pointer completion_string, ); -/// Determine the number of diagnostics produced for the given translation unit. +/// Determine the number of diagnostics produced for the given +/// translation unit. int clang_getNumDiagnostics( ffi.Pointer Unit, ) { @@ -3080,6 +3635,11 @@ typedef _dart_clang_getPointeeType_wrap = ffi.Pointer Function( ); /// Retrieve a remapping. +/// +/// \param path the path that contains metadata about remappings. +/// +/// \returns the requested remapping. This remapping must be freed +/// via a call to \c clang_remap_dispose(). Can return NULL if an error occurred. ffi.Pointer clang_getRemappings( ffi.Pointer path, ) { @@ -3101,6 +3661,13 @@ typedef _dart_clang_getRemappings = ffi.Pointer Function( ); /// Retrieve a remapping. +/// +/// \param filePaths pointer to an array of file paths containing remapping info. +/// +/// \param numFiles number of file paths. +/// +/// \returns the requested remapping. This remapping must be freed +/// via a call to \c clang_remap_dispose(). Can return NULL if an error occurred. ffi.Pointer clang_getRemappingsFromFileList( ffi.Pointer> filePaths, int numFiles, @@ -3147,6 +3714,9 @@ typedef _dart_clang_getResultType_wrap = ffi.Pointer Function( ); /// Retrieve all ranges that were skipped by the preprocessor. +/// +/// The preprocessor will skip lines when they are surrounded by an +/// if/ifdef/ifndef directive whose condition does not evaluate to true. ffi.Pointer clang_getSkippedRanges( ffi.Pointer tu, ffi.Pointer file, @@ -3171,7 +3741,8 @@ typedef _dart_clang_getSkippedRanges = ffi.Pointer Function( ffi.Pointer file, ); -/// Returns the human-readable null-terminated C string that represents the name of the memory category. This string should never be freed. +/// Returns the human-readable null-terminated C string that represents +/// the name of the memory category. This string should never be freed. ffi.Pointer clang_getTUResourceUsageName( int kind, ) { @@ -3216,6 +3787,8 @@ typedef _dart_clang_getTranslationUnitCursor_wrap = ffi.Pointer ); /// Get target information for this translation unit. +/// +/// The CXTargetInfo object cannot outlive the CXTranslationUnit object. ffi.Pointer clang_getTranslationUnitTargetInfo( ffi.Pointer CTUnit, ) { @@ -3324,7 +3897,29 @@ typedef _dart_clang_getTypedefDeclUnderlyingType_wrap = ffi.Pointer ffi.Pointer cxcursor, ); -/// Index the given source file and the translation unit corresponding to that file via callbacks implemented through #IndexerCallbacks. +/// Index the given source file and the translation unit corresponding +/// to that file via callbacks implemented through #IndexerCallbacks. +/// +/// \param client_data pointer data supplied by the client, which will +/// be passed to the invoked callbacks. +/// +/// \param index_callbacks Pointer to indexing callbacks that the client +/// implements. +/// +/// \param index_callbacks_size Size of #IndexerCallbacks structure that gets +/// passed in index_callbacks. +/// +/// \param index_options A bitmask of options that affects how indexing is +/// performed. This should be a bitwise OR of the CXIndexOpt_XXX flags. +/// +/// \param[out] out_TU pointer to store a \c CXTranslationUnit that can be +/// reused after indexing is finished. Set to \c NULL if you do not require it. +/// +/// \returns 0 on success or if there were errors from which the compiler could +/// recover. If there is a failure from which there is no recovery, returns +/// a non-zero \c CXErrorCode. +/// +/// The rest of the parameters are the same as #clang_parseTranslationUnit. int clang_indexSourceFile( ffi.Pointer arg0, ffi.Pointer client_data, @@ -3389,7 +3984,9 @@ typedef _dart_clang_indexSourceFile = int Function( int TU_options, ); -/// Same as clang_indexSourceFile but requires a full command line for command_line_args including argv[0]. This is useful if the standard library paths are relative to the binary. +/// Same as clang_indexSourceFile but requires a full command line +/// for \c command_line_args including argv[0]. This is useful if the standard +/// library paths are relative to the binary. int clang_indexSourceFileFullArgv( ffi.Pointer arg0, ffi.Pointer client_data, @@ -3454,7 +4051,20 @@ typedef _dart_clang_indexSourceFileFullArgv = int Function( int TU_options, ); -/// Index the given translation unit via callbacks implemented through #IndexerCallbacks. +/// Index the given translation unit via callbacks implemented through +/// #IndexerCallbacks. +/// +/// The order of callback invocations is not guaranteed to be the same as +/// when indexing a source file. The high level order will be: +/// +/// -Preprocessor callbacks invocations +/// -Declaration/reference callbacks invocations +/// -Diagnostic callback invocations +/// +/// The parameters are the same as #clang_indexSourceFile. +/// +/// \returns If there is a failure from which there is no recovery, returns +/// non-zero, otherwise returns 0. int clang_indexTranslationUnit( ffi.Pointer arg0, ffi.Pointer client_data, @@ -3518,7 +4128,8 @@ typedef _dart_clang_index_getCXXClassDeclInfo ffi.Pointer arg0, ); -/// For retrieving a custom CXIdxClientContainer attached to a container. +/// For retrieving a custom CXIdxClientContainer attached to a +/// container. ffi.Pointer clang_index_getClientContainer( ffi.Pointer arg0, ) { @@ -3728,7 +4339,8 @@ typedef _dart_clang_index_isEntityObjCContainerKind = int Function( int arg0, ); -/// For setting a custom CXIdxClientContainer attached to a container. +/// For setting a custom CXIdxClientContainer attached to a +/// container. void clang_index_setClientContainer( ffi.Pointer arg0, ffi.Pointer arg1, @@ -3841,7 +4453,9 @@ typedef _dart_clang_isExpression = int Function( int arg0, ); -/// Determine whether the given header is guarded against multiple inclusions, either with the conventional #ifndef/#define/#endif macro guards or with #pragma once. +/// Determine whether the given header is guarded against +/// multiple inclusions, either with the conventional +/// \#ifndef/\#define/\#endif macro guards or with \#pragma once. int clang_isFileMultipleIncludeGuarded( ffi.Pointer tu, ffi.Pointer file, @@ -3868,7 +4482,8 @@ typedef _dart_clang_isFileMultipleIncludeGuarded = int Function( ffi.Pointer file, ); -/// Determine whether the given cursor kind represents an invalid cursor. +/// Determine whether the given cursor kind represents an invalid +/// cursor. int clang_isInvalid( int arg0, ) { @@ -3889,7 +4504,8 @@ typedef _dart_clang_isInvalid = int Function( int arg0, ); -/// * Determine whether the given cursor represents a preprocessing element, such as a preprocessor directive or macro instantiation. +/// Determine whether the given cursor represents a preprocessing +/// element, such as a preprocessor directive or macro instantiation. int clang_isPreprocessing( int arg0, ) { @@ -3910,7 +4526,12 @@ typedef _dart_clang_isPreprocessing = int Function( int arg0, ); -/// Determine whether the given cursor kind represents a simple reference. +/// Determine whether the given cursor kind represents a simple +/// reference. +/// +/// Note that other kinds of cursors (such as expressions) can also refer to +/// other cursors. Use clang_getCursorReferenced() to determine whether a +/// particular cursor refers to another entity. int clang_isReference( int arg0, ) { @@ -3952,7 +4573,8 @@ typedef _dart_clang_isStatement = int Function( int arg0, ); -/// Determine whether the given cursor kind represents a translation unit. +/// Determine whether the given cursor kind represents a translation +/// unit. int clang_isTranslationUnit( int arg0, ) { @@ -3973,7 +4595,8 @@ typedef _dart_clang_isTranslationUnit = int Function( int arg0, ); -/// * Determine whether the given cursor represents a currently unexposed piece of the AST (e.g., CXCursor_UnexposedStmt). +/// Determine whether the given cursor represents a currently +/// unexposed piece of the AST (e.g., CXCursor_UnexposedStmt). int clang_isUnexposed( int arg0, ) { @@ -3994,7 +4617,17 @@ typedef _dart_clang_isUnexposed = int Function( int arg0, ); -/// Deserialize a set of diagnostics from a Clang diagnostics bitcode file. +/// Deserialize a set of diagnostics from a Clang diagnostics bitcode +/// file. +/// +/// \param file The name of the file to deserialize. +/// \param error A pointer to a enum value recording if there was a problem +/// deserializing the diagnostics. +/// \param errorString A pointer to a CXString for recording the error string +/// if the file was not successfully loaded. +/// +/// \returns A loaded CXDiagnosticSet if successful, and NULL otherwise. These +/// diagnostics should be released using clang_disposeDiagnosticSet(). ffi.Pointer clang_loadDiagnostics( ffi.Pointer file, ffi.Pointer error, @@ -4023,7 +4656,10 @@ typedef _dart_clang_loadDiagnostics = ffi.Pointer Function( ffi.Pointer errorString, ); -/// Same as clang_parseTranslationUnit2, but returns the CXTranslationUnit instead of an error code. In case of an error this routine returns a NULL CXTranslationUnit, without further detailed error codes. +/// Same as \c clang_parseTranslationUnit2, but returns +/// the \c CXTranslationUnit instead of an error code. In case of an error this +/// routine returns a \c NULL \c CXTranslationUnit, without further detailed +/// error codes. ffi.Pointer clang_parseTranslationUnit( ffi.Pointer CIdx, ffi.Pointer source_filename, @@ -4070,7 +4706,48 @@ typedef _dart_clang_parseTranslationUnit = ffi.Pointer int options, ); -/// Parse the given source file and the translation unit corresponding to that file. +/// Parse the given source file and the translation unit corresponding +/// to that file. +/// +/// This routine is the main entry point for the Clang C API, providing the +/// ability to parse a source file into a translation unit that can then be +/// queried by other functions in the API. This routine accepts a set of +/// command-line arguments so that the compilation can be configured in the same +/// way that the compiler is configured on the command line. +/// +/// \param CIdx The index object with which the translation unit will be +/// associated. +/// +/// \param source_filename The name of the source file to load, or NULL if the +/// source file is included in \c command_line_args. +/// +/// \param command_line_args The command-line arguments that would be +/// passed to the \c clang executable if it were being invoked out-of-process. +/// These command-line options will be parsed and will affect how the translation +/// unit is parsed. Note that the following options are ignored: '-c', +/// '-emit-ast', '-fsyntax-only' (which is the default), and '-o \'. +/// +/// \param num_command_line_args The number of command-line arguments in +/// \c command_line_args. +/// +/// \param unsaved_files the files that have not yet been saved to disk +/// but may be required for parsing, including the contents of +/// those files. The contents and name of these files (as specified by +/// CXUnsavedFile) are copied when necessary, so the client only needs to +/// guarantee their validity until the call to this function returns. +/// +/// \param num_unsaved_files the number of unsaved file entries in \p +/// unsaved_files. +/// +/// \param options A bitmask of options that affects how the translation unit +/// is managed but not its compilation. This should be a bitwise OR of the +/// CXTranslationUnit_XXX flags. +/// +/// \param[out] out_TU A non-NULL pointer to store the created +/// \c CXTranslationUnit, describing the parsed code and containing any +/// diagnostics produced by the compiler. +/// +/// \returns Zero on success, otherwise returns an error code. int clang_parseTranslationUnit2( ffi.Pointer CIdx, ffi.Pointer source_filename, @@ -4119,7 +4796,9 @@ typedef _dart_clang_parseTranslationUnit2 = int Function( ffi.Pointer> out_TU, ); -/// Same as clang_parseTranslationUnit2 but requires a full command line for command_line_args including argv[0]. This is useful if the standard library paths are relative to the binary. +/// Same as clang_parseTranslationUnit2 but requires a full command line +/// for \c command_line_args including argv[0]. This is useful if the standard +/// library paths are relative to the binary. int clang_parseTranslationUnit2FullArgv( ffi.Pointer CIdx, ffi.Pointer source_filename, @@ -4192,6 +4871,11 @@ typedef _dart_clang_remap_dispose = void Function( ); /// Get the original and the associated filename from the remapping. +/// +/// \param original If non-NULL, will be set to the original filename. +/// +/// \param transformed If non-NULL, will be set to the filename that the original +/// is associated with. void clang_remap_getFilenames( ffi.Pointer arg0, int index, @@ -4246,6 +4930,42 @@ typedef _dart_clang_remap_getNumFiles = int Function( ); /// Reparse the source files that produced this translation unit. +/// +/// This routine can be used to re-parse the source files that originally +/// created the given translation unit, for example because those source files +/// have changed (either on disk or as passed via \p unsaved_files). The +/// source code will be reparsed with the same command-line options as it +/// was originally parsed. +/// +/// Reparsing a translation unit invalidates all cursors and source locations +/// that refer into that translation unit. This makes reparsing a translation +/// unit semantically equivalent to destroying the translation unit and then +/// creating a new translation unit with the same command-line arguments. +/// However, it may be more efficient to reparse a translation +/// unit using this routine. +/// +/// \param TU The translation unit whose contents will be re-parsed. The +/// translation unit must originally have been built with +/// \c clang_createTranslationUnitFromSourceFile(). +/// +/// \param num_unsaved_files The number of unsaved file entries in \p +/// unsaved_files. +/// +/// \param unsaved_files The files that have not yet been saved to disk +/// but may be required for parsing, including the contents of +/// those files. The contents and name of these files (as specified by +/// CXUnsavedFile) are copied when necessary, so the client only needs to +/// guarantee their validity until the call to this function returns. +/// +/// \param options A bitset of options composed of the flags in CXReparse_Flags. +/// The function \c clang_defaultReparseOptions() produces a default set of +/// options recommended for most uses, based on the translation unit. +/// +/// \returns 0 if the sources could be reparsed. A non-zero error code will be +/// returned if reparsing was impossible, such that the translation unit is +/// invalid. In such cases, the only valid call for \c TU is +/// \c clang_disposeTranslationUnit(TU). The error codes returned by this +/// routine are described by the \c CXErrorCode enum. int clang_reparseTranslationUnit( ffi.Pointer TU, int num_unsaved_files, @@ -4278,7 +4998,27 @@ typedef _dart_clang_reparseTranslationUnit = int Function( int options, ); -/// Saves a translation unit into a serialized representation of that translation unit on disk. +/// Saves a translation unit into a serialized representation of +/// that translation unit on disk. +/// +/// Any translation unit that was parsed without error can be saved +/// into a file. The translation unit can then be deserialized into a +/// new \c CXTranslationUnit with \c clang_createTranslationUnit() or, +/// if it is an incomplete translation unit that corresponds to a +/// header, used as a precompiled header when parsing other translation +/// units. +/// +/// \param TU The translation unit to save. +/// +/// \param FileName The file to which the translation unit will be saved. +/// +/// \param options A bitmask of options that affects how the translation unit +/// is saved. This should be a bitwise OR of the +/// CXSaveTranslationUnit_XXX flags. +/// +/// \returns A value that will match one of the enumerators of the CXSaveError +/// enumeration. Zero (CXSaveError_None) indicates that the translation unit was +/// saved successfully, while a non-zero value indicates that a problem occurred. int clang_saveTranslationUnit( ffi.Pointer TU, ffi.Pointer FileName, @@ -4307,7 +5047,11 @@ typedef _dart_clang_saveTranslationUnit = int Function( int options, ); -/// Sort the code-completion results in case-insensitive alphabetical order. +/// Sort the code-completion results in case-insensitive alphabetical +/// order. +/// +/// \param Results The set of results to sort. +/// \param NumResults The number of results in \p Results. void clang_sortCodeCompletionResults( ffi.Pointer Results, int NumResults, @@ -4334,6 +5078,10 @@ typedef _dart_clang_sortCodeCompletionResults = void Function( ); /// Suspend a translation unit in order to free memory associated with it. +/// +/// A suspended translation unit uses significantly less memory but on the other +/// side does not support any other calls than \c clang_reparseTranslationUnit +/// to resume it or \c clang_disposeTranslationUnit to dispose it completely. int clang_suspendTranslationUnit( ffi.Pointer arg0, ) { @@ -4355,6 +5103,9 @@ typedef _dart_clang_suspendTranslationUnit = int Function( ); /// Enable/disable crash recovery. +/// +/// \param isEnabled Flag to indicate if crash recovery is enabled. A non-zero +/// value enables crash recovery, while 0 disables it. void clang_toggleCrashRecovery( int isEnabled, ) { @@ -4375,7 +5126,8 @@ typedef _dart_clang_toggleCrashRecovery = void Function( int isEnabled, ); -/// Visitor is a function pointer with parameters having pointers to cxcursor instead of cxcursor by default. +/// Visitor is a function pointer with parameters having pointers to cxcursor +/// instead of cxcursor by default. int clang_visitChildren_wrap( ffi.Pointer parent, ffi.Pointer> _modifiedVisitor, diff --git a/example/libclang-example/pubspec.yaml b/example/libclang-example/pubspec.yaml index bd000c69..d4dc2fd2 100644 --- a/example/libclang-example/pubspec.yaml +++ b/example/libclang-example/pubspec.yaml @@ -59,5 +59,5 @@ ffigen: unsigned long long: 8 enum: 4 - # True by default - extract-comments: true + # Doc Comments for generated binings: Can be full, brief(default) or none + comments: full diff --git a/lib/src/code_generator/struc.dart b/lib/src/code_generator/struc.dart index 391dc2ed..4cb51526 100644 --- a/lib/src/code_generator/struc.dart +++ b/lib/src/code_generator/struc.dart @@ -71,10 +71,16 @@ class Struc extends Binding { s.write(arrayHelper.declarationString(w)); helpers.add(arrayHelper); } else { + const depth = ' '; + if (m.dartDoc != null) { + s.write(depth + '/// '); + s.writeAll(m.dartDoc.split('\n'), '\n' + depth + '/// '); + s.write('\n'); + } if (m.type.isPrimitive) { - s.write(' @${m.type.getCType(w)}()\n'); + s.write('$depth@${m.type.getCType(w)}()\n'); } - s.write(' ${m.type.getDartType(w)} ${m.name};\n\n'); + s.write('$depth${m.type.getDartType(w)} ${m.name};\n\n'); } } s.write('}\n\n'); @@ -88,10 +94,11 @@ class Struc extends Binding { } class Member { + final String dartDoc; final String name; final Type type; - const Member({this.name, this.type}); + const Member({this.name, this.type, this.dartDoc}); } // Helper bindings for struct array. diff --git a/lib/src/config_provider/config.dart b/lib/src/config_provider/config.dart index 89f55c20..49cda0ca 100644 --- a/lib/src/config_provider/config.dart +++ b/lib/src/config_provider/config.dart @@ -59,8 +59,8 @@ class Config { /// If typedef of supported types(int8_t) should be directly used. bool useSupportedTypedefs; - /// If tool should extract doc comment from bindings. - bool extractComments; + /// Extracted Doc comment type. + String comment; /// Manually creating configurations. /// @@ -77,7 +77,7 @@ class Config { this.enumClassFilters, this.sort = false, this.useSupportedTypedefs = true, - this.extractComments = true, + this.comment, }); Config._(); @@ -243,13 +243,13 @@ class Config { extractedResult: (dynamic result) => useSupportedTypedefs = result as bool, ), - strings.extractComments: Specification( - description: 'whether or not to extract comments from bindings', + strings.comments: Specification( + description: 'Type of comment to extract', isRequired: false, - validator: booleanValidator, - extractor: booleanExtractor, - defaultValue: true, - extractedResult: (dynamic result) => extractComments = result as bool, + validator: commentValidator, + extractor: commentExtractor, + defaultValue: strings.brief, + extractedResult: (dynamic result) => comment = result as String, ), }; } diff --git a/lib/src/config_provider/spec_utils.dart b/lib/src/config_provider/spec_utils.dart index 683d53dd..3544330d 100644 --- a/lib/src/config_provider/spec_utils.dart +++ b/lib/src/config_provider/spec_utils.dart @@ -205,7 +205,8 @@ bool filterValidator(String name, dynamic value) { for (final subkey in value[key].keys) { if (subkey == strings.matches || subkey == strings.names) { if (value[key][subkey] is! YamlList) { - _logger.severe("Expected '$name -> $key -> $subkey' to be a List."); + _logger + .severe("Expected '$name -> $key -> $subkey' to be a List."); _result = false; } } else { @@ -239,3 +240,20 @@ SupportedNativeType nativeSupportedType(int value, {bool signed = true}) { 'Unsupported value given to sizemap, Allowed values for sizes are: 1, 2, 4, 8'); } } + +String commentExtractor(dynamic value) => value as String; + +bool commentValidator(String name, dynamic value) { + if (value is! String) { + _logger.severe("Expected value of key '$name' to be a String."); + return false; + } else { + if (strings.commentTypeSet.contains(value as String)) { + return true; + } else { + _logger.severe( + "Value of key '$name' must be one of the following - ${strings.commentTypeSet}."); + return false; + } + } +} diff --git a/lib/src/header_parser/clang_bindings/clang_bindings.dart b/lib/src/header_parser/clang_bindings/clang_bindings.dart index f7019710..1cf40a30 100644 --- a/lib/src/header_parser/clang_bindings/clang_bindings.dart +++ b/lib/src/header_parser/clang_bindings/clang_bindings.dart @@ -11,14 +11,23 @@ void init(ffi.DynamicLibrary dylib) { _dylib = dylib; } -/// Describes how the traversal of the children of a particular cursor should proceed after visiting a particular child cursor. +/// Describes how the traversal of the children of a particular cursor should +/// proceed after visiting a particular child cursor. class CXChildVisitResult { + /// Terminates the cursor traversal. static const int CXChildVisit_Break = 0; + + /// Continues the cursor traversal with the next sibling of the cursor just + /// visited, without visiting its children. static const int CXChildVisit_Continue = 1; + + /// Recursively traverse the children of this cursor, using the same visitor + /// and client data. static const int CXChildVisit_Recurse = 2; } -/// A cursor representing some element in the abstract syntax tree for a translation unit. +/// A cursor representing some element in the abstract syntax tree for a +/// translation unit. class CXCursor extends ffi.Struct { @ffi.Int32() int kind; @@ -84,44 +93,122 @@ class _ArrayHelper_CXCursor_data { /// Describes the kind of entity that a cursor refers to. class CXCursorKind { + /// A declaration whose specific kind is not exposed via this interface. static const int CXCursor_UnexposedDecl = 1; + + /// A C or C++ struct. static const int CXCursor_StructDecl = 2; + + /// A C or C++ union. static const int CXCursor_UnionDecl = 3; + + /// A C++ class. static const int CXCursor_ClassDecl = 4; + + /// An enumeration. static const int CXCursor_EnumDecl = 5; + + /// A field (in C) or non-static data member (in C++) in a struct, union, or + /// C++ class. static const int CXCursor_FieldDecl = 6; + + /// An enumerator constant. static const int CXCursor_EnumConstantDecl = 7; + + /// A function. static const int CXCursor_FunctionDecl = 8; + + /// A variable. static const int CXCursor_VarDecl = 9; + + /// A function or method parameter. static const int CXCursor_ParmDecl = 10; + + /// An Objective-C @interface. static const int CXCursor_ObjCInterfaceDecl = 11; + + /// An Objective-C @interface for a category. static const int CXCursor_ObjCCategoryDecl = 12; + + /// An Objective-C @protocol declaration. static const int CXCursor_ObjCProtocolDecl = 13; + + /// An Objective-C @property declaration. static const int CXCursor_ObjCPropertyDecl = 14; + + /// An Objective-C instance variable. static const int CXCursor_ObjCIvarDecl = 15; + + /// An Objective-C instance method. static const int CXCursor_ObjCInstanceMethodDecl = 16; + + /// An Objective-C class method. static const int CXCursor_ObjCClassMethodDecl = 17; + + /// An Objective-C @implementation. static const int CXCursor_ObjCImplementationDecl = 18; + + /// An Objective-C @implementation for a category. static const int CXCursor_ObjCCategoryImplDecl = 19; + + /// A typedef. static const int CXCursor_TypedefDecl = 20; + + /// A C++ class method. static const int CXCursor_CXXMethod = 21; + + /// A C++ namespace. static const int CXCursor_Namespace = 22; + + /// A linkage specification, e.g. 'extern "C"'. static const int CXCursor_LinkageSpec = 23; + + /// A C++ constructor. static const int CXCursor_Constructor = 24; + + /// A C++ destructor. static const int CXCursor_Destructor = 25; + + /// A C++ conversion function. static const int CXCursor_ConversionFunction = 26; + + /// A C++ template type parameter. static const int CXCursor_TemplateTypeParameter = 27; + + /// A C++ non-type template parameter. static const int CXCursor_NonTypeTemplateParameter = 28; + + /// A C++ template template parameter. static const int CXCursor_TemplateTemplateParameter = 29; + + /// A C++ function template. static const int CXCursor_FunctionTemplate = 30; + + /// A C++ class template. static const int CXCursor_ClassTemplate = 31; + + /// A C++ class template partial specialization. static const int CXCursor_ClassTemplatePartialSpecialization = 32; + + /// A C++ namespace alias declaration. static const int CXCursor_NamespaceAlias = 33; + + /// A C++ using directive. static const int CXCursor_UsingDirective = 34; + + /// A C++ using declaration. static const int CXCursor_UsingDeclaration = 35; + + /// A C++ alias declaration static const int CXCursor_TypeAliasDecl = 36; + + /// An Objective-C @synthesize definition. static const int CXCursor_ObjCSynthesizeDecl = 37; + + /// An Objective-C @dynamic definition. static const int CXCursor_ObjCDynamicDecl = 38; + + /// An access specifier. static const int CXCursor_CXXAccessSpecifier = 39; static const int CXCursor_FirstDecl = 1; static const int CXCursor_LastDecl = 39; @@ -129,13 +216,31 @@ class CXCursorKind { static const int CXCursor_ObjCSuperClassRef = 40; static const int CXCursor_ObjCProtocolRef = 41; static const int CXCursor_ObjCClassRef = 42; + + /// A reference to a type declaration. static const int CXCursor_TypeRef = 43; static const int CXCursor_CXXBaseSpecifier = 44; + + /// A reference to a class template, function template, template template + /// parameter, or class template partial specialization. static const int CXCursor_TemplateRef = 45; + + /// A reference to a namespace or namespace alias. static const int CXCursor_NamespaceRef = 46; + + /// A reference to a member of a struct, union, or class that occurs in some + /// non-expression context, e.g., a designated initializer. static const int CXCursor_MemberRef = 47; + + /// A reference to a labeled statement. static const int CXCursor_LabelRef = 48; + + /// A reference to a set of overloaded functions or function templates that + /// has not yet been resolved to a specific function or function template. static const int CXCursor_OverloadedDeclRef = 49; + + /// A reference to a variable that occurs in some non-expression context, + /// e.g., a C++ lambda capture list. static const int CXCursor_VariableRef = 50; static const int CXCursor_LastRef = 50; static const int CXCursor_FirstInvalid = 70; @@ -145,149 +250,432 @@ class CXCursorKind { static const int CXCursor_InvalidCode = 73; static const int CXCursor_LastInvalid = 73; static const int CXCursor_FirstExpr = 100; + + /// An expression whose specific kind is not exposed via this interface. static const int CXCursor_UnexposedExpr = 100; + + /// An expression that refers to some value declaration, such as a function, + /// variable, or enumerator. static const int CXCursor_DeclRefExpr = 101; + + /// An expression that refers to a member of a struct, union, class, + /// Objective-C class, etc. static const int CXCursor_MemberRefExpr = 102; + + /// An expression that calls a function. static const int CXCursor_CallExpr = 103; + + /// An expression that sends a message to an Objective-C object or class. static const int CXCursor_ObjCMessageExpr = 104; + + /// An expression that represents a block literal. static const int CXCursor_BlockExpr = 105; + + /// An integer literal. static const int CXCursor_IntegerLiteral = 106; + + /// A floating point number literal. static const int CXCursor_FloatingLiteral = 107; + + /// An imaginary number literal. static const int CXCursor_ImaginaryLiteral = 108; + + /// A string literal. static const int CXCursor_StringLiteral = 109; + + /// A character literal. static const int CXCursor_CharacterLiteral = 110; + + /// A parenthesized expression, e.g. "(1)". static const int CXCursor_ParenExpr = 111; + + /// This represents the unary-expression's (except sizeof and alignof). static const int CXCursor_UnaryOperator = 112; + + /// [C99 6.5.2.1] Array Subscripting. static const int CXCursor_ArraySubscriptExpr = 113; + + /// A builtin binary operation expression such as "x + y" or "x <= y". static const int CXCursor_BinaryOperator = 114; + + /// Compound assignment such as "+=". static const int CXCursor_CompoundAssignOperator = 115; + + /// The ?: ternary operator. static const int CXCursor_ConditionalOperator = 116; + + /// An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ + /// [expr.cast]), which uses the syntax (Type)expr. static const int CXCursor_CStyleCastExpr = 117; + + /// [C99 6.5.2.5] static const int CXCursor_CompoundLiteralExpr = 118; + + /// Describes an C or C++ initializer list. static const int CXCursor_InitListExpr = 119; + + /// The GNU address of label extension, representing &&label. static const int CXCursor_AddrLabelExpr = 120; + + /// This is the GNU Statement Expression extension: ({int X=4; X;}) static const int CXCursor_StmtExpr = 121; + + /// Represents a C11 generic selection. static const int CXCursor_GenericSelectionExpr = 122; + + /// Implements the GNU __null extension, which is a name for a null pointer + /// constant that has integral type (e.g., int or long) and is the same size + /// and alignment as a pointer. static const int CXCursor_GNUNullExpr = 123; + + /// C++'s static_cast<> expression. static const int CXCursor_CXXStaticCastExpr = 124; + + /// C++'s dynamic_cast<> expression. static const int CXCursor_CXXDynamicCastExpr = 125; + + /// C++'s reinterpret_cast<> expression. static const int CXCursor_CXXReinterpretCastExpr = 126; + + /// C++'s const_cast<> expression. static const int CXCursor_CXXConstCastExpr = 127; + + /// Represents an explicit C++ type conversion that uses "functional" notion + /// (C++ [expr.type.conv]). static const int CXCursor_CXXFunctionalCastExpr = 128; + + /// A C++ typeid expression (C++ [expr.typeid]). static const int CXCursor_CXXTypeidExpr = 129; + + /// [C++ 2.13.5] C++ Boolean Literal. static const int CXCursor_CXXBoolLiteralExpr = 130; + + /// [C++0x 2.14.7] C++ Pointer Literal. static const int CXCursor_CXXNullPtrLiteralExpr = 131; + + /// Represents the "this" expression in C++ static const int CXCursor_CXXThisExpr = 132; + + /// [C++ 15] C++ Throw Expression. static const int CXCursor_CXXThrowExpr = 133; + + /// A new expression for memory allocation and constructor calls, e.g: "new + /// CXXNewExpr(foo)". static const int CXCursor_CXXNewExpr = 134; + + /// A delete expression for memory deallocation and destructor calls, e.g. + /// "delete[] pArray". static const int CXCursor_CXXDeleteExpr = 135; + + /// A unary expression. (noexcept, sizeof, or other traits) static const int CXCursor_UnaryExpr = 136; + + /// An Objective-C string literal i.e. "foo". static const int CXCursor_ObjCStringLiteral = 137; + + /// An Objective-C @encode expression. static const int CXCursor_ObjCEncodeExpr = 138; + + /// An Objective-C @selector expression. static const int CXCursor_ObjCSelectorExpr = 139; + + /// An Objective-C @protocol expression. static const int CXCursor_ObjCProtocolExpr = 140; + + /// An Objective-C "bridged" cast expression, which casts between Objective-C + /// pointers and C pointers, transferring ownership in the process. static const int CXCursor_ObjCBridgedCastExpr = 141; + + /// Represents a C++0x pack expansion that produces a sequence of expressions. static const int CXCursor_PackExpansionExpr = 142; + + /// Represents an expression that computes the length of a parameter pack. static const int CXCursor_SizeOfPackExpr = 143; static const int CXCursor_LambdaExpr = 144; + + /// Objective-c Boolean Literal. static const int CXCursor_ObjCBoolLiteralExpr = 145; + + /// Represents the "self" expression in an Objective-C method. static const int CXCursor_ObjCSelfExpr = 146; + + /// OpenMP 4.0 [2.4, Array Section]. static const int CXCursor_OMPArraySectionExpr = 147; + + /// Represents an (...) check. static const int CXCursor_ObjCAvailabilityCheckExpr = 148; + + /// Fixed point literal static const int CXCursor_FixedPointLiteral = 149; static const int CXCursor_LastExpr = 149; static const int CXCursor_FirstStmt = 200; + + /// A statement whose specific kind is not exposed via this interface. static const int CXCursor_UnexposedStmt = 200; + + /// A labelled statement in a function. static const int CXCursor_LabelStmt = 201; + + /// A group of statements like { stmt stmt }. static const int CXCursor_CompoundStmt = 202; + + /// A case statement. static const int CXCursor_CaseStmt = 203; + + /// A default statement. static const int CXCursor_DefaultStmt = 204; + + /// An if statement static const int CXCursor_IfStmt = 205; + + /// A switch statement. static const int CXCursor_SwitchStmt = 206; + + /// A while statement. static const int CXCursor_WhileStmt = 207; + + /// A do statement. static const int CXCursor_DoStmt = 208; + + /// A for statement. static const int CXCursor_ForStmt = 209; + + /// A goto statement. static const int CXCursor_GotoStmt = 210; + + /// An indirect goto statement. static const int CXCursor_IndirectGotoStmt = 211; + + /// A continue statement. static const int CXCursor_ContinueStmt = 212; + + /// A break statement. static const int CXCursor_BreakStmt = 213; + + /// A return statement. static const int CXCursor_ReturnStmt = 214; + + /// A GCC inline assembly statement extension. static const int CXCursor_GCCAsmStmt = 215; static const int CXCursor_AsmStmt = 215; + + /// Objective-C's overall @try-@catch-@finally statement. static const int CXCursor_ObjCAtTryStmt = 216; + + /// Objective-C's @catch statement. static const int CXCursor_ObjCAtCatchStmt = 217; + + /// Objective-C's @finally statement. static const int CXCursor_ObjCAtFinallyStmt = 218; + + /// Objective-C's @throw statement. static const int CXCursor_ObjCAtThrowStmt = 219; + + /// Objective-C's @synchronized statement. static const int CXCursor_ObjCAtSynchronizedStmt = 220; + + /// Objective-C's autorelease pool statement. static const int CXCursor_ObjCAutoreleasePoolStmt = 221; + + /// Objective-C's collection statement. static const int CXCursor_ObjCForCollectionStmt = 222; + + /// C++'s catch statement. static const int CXCursor_CXXCatchStmt = 223; + + /// C++'s try statement. static const int CXCursor_CXXTryStmt = 224; + + /// C++'s for (* : *) statement. static const int CXCursor_CXXForRangeStmt = 225; + + /// Windows Structured Exception Handling's try statement. static const int CXCursor_SEHTryStmt = 226; + + /// Windows Structured Exception Handling's except statement. static const int CXCursor_SEHExceptStmt = 227; + + /// Windows Structured Exception Handling's finally statement. static const int CXCursor_SEHFinallyStmt = 228; + + /// A MS inline assembly statement extension. static const int CXCursor_MSAsmStmt = 229; + + /// The null statement ";": C99 6.8.3p3. static const int CXCursor_NullStmt = 230; + + /// Adaptor class for mixing declarations with statements and expressions. static const int CXCursor_DeclStmt = 231; + + /// OpenMP parallel directive. static const int CXCursor_OMPParallelDirective = 232; + + /// OpenMP SIMD directive. static const int CXCursor_OMPSimdDirective = 233; + + /// OpenMP for directive. static const int CXCursor_OMPForDirective = 234; + + /// OpenMP sections directive. static const int CXCursor_OMPSectionsDirective = 235; + + /// OpenMP section directive. static const int CXCursor_OMPSectionDirective = 236; + + /// OpenMP single directive. static const int CXCursor_OMPSingleDirective = 237; + + /// OpenMP parallel for directive. static const int CXCursor_OMPParallelForDirective = 238; + + /// OpenMP parallel sections directive. static const int CXCursor_OMPParallelSectionsDirective = 239; + + /// OpenMP task directive. static const int CXCursor_OMPTaskDirective = 240; + + /// OpenMP master directive. static const int CXCursor_OMPMasterDirective = 241; + + /// OpenMP critical directive. static const int CXCursor_OMPCriticalDirective = 242; + + /// OpenMP taskyield directive. static const int CXCursor_OMPTaskyieldDirective = 243; + + /// OpenMP barrier directive. static const int CXCursor_OMPBarrierDirective = 244; + + /// OpenMP taskwait directive. static const int CXCursor_OMPTaskwaitDirective = 245; + + /// OpenMP flush directive. static const int CXCursor_OMPFlushDirective = 246; + + /// Windows Structured Exception Handling's leave statement. static const int CXCursor_SEHLeaveStmt = 247; + + /// OpenMP ordered directive. static const int CXCursor_OMPOrderedDirective = 248; + + /// OpenMP atomic directive. static const int CXCursor_OMPAtomicDirective = 249; + + /// OpenMP for SIMD directive. static const int CXCursor_OMPForSimdDirective = 250; + + /// OpenMP parallel for SIMD directive. static const int CXCursor_OMPParallelForSimdDirective = 251; + + /// OpenMP target directive. static const int CXCursor_OMPTargetDirective = 252; + + /// OpenMP teams directive. static const int CXCursor_OMPTeamsDirective = 253; + + /// OpenMP taskgroup directive. static const int CXCursor_OMPTaskgroupDirective = 254; + + /// OpenMP cancellation point directive. static const int CXCursor_OMPCancellationPointDirective = 255; + + /// OpenMP cancel directive. static const int CXCursor_OMPCancelDirective = 256; + + /// OpenMP target data directive. static const int CXCursor_OMPTargetDataDirective = 257; + + /// OpenMP taskloop directive. static const int CXCursor_OMPTaskLoopDirective = 258; + + /// OpenMP taskloop simd directive. static const int CXCursor_OMPTaskLoopSimdDirective = 259; + + /// OpenMP distribute directive. static const int CXCursor_OMPDistributeDirective = 260; + + /// OpenMP target enter data directive. static const int CXCursor_OMPTargetEnterDataDirective = 261; + + /// OpenMP target exit data directive. static const int CXCursor_OMPTargetExitDataDirective = 262; + + /// OpenMP target parallel directive. static const int CXCursor_OMPTargetParallelDirective = 263; + + /// OpenMP target parallel for directive. static const int CXCursor_OMPTargetParallelForDirective = 264; + + /// OpenMP target update directive. static const int CXCursor_OMPTargetUpdateDirective = 265; + + /// OpenMP distribute parallel for directive. static const int CXCursor_OMPDistributeParallelForDirective = 266; + + /// OpenMP distribute parallel for simd directive. static const int CXCursor_OMPDistributeParallelForSimdDirective = 267; + + /// OpenMP distribute simd directive. static const int CXCursor_OMPDistributeSimdDirective = 268; + + /// OpenMP target parallel for simd directive. static const int CXCursor_OMPTargetParallelForSimdDirective = 269; + + /// OpenMP target simd directive. static const int CXCursor_OMPTargetSimdDirective = 270; + + /// OpenMP teams distribute directive. static const int CXCursor_OMPTeamsDistributeDirective = 271; + + /// OpenMP teams distribute simd directive. static const int CXCursor_OMPTeamsDistributeSimdDirective = 272; + + /// OpenMP teams distribute parallel for simd directive. static const int CXCursor_OMPTeamsDistributeParallelForSimdDirective = 273; + + /// OpenMP teams distribute parallel for directive. static const int CXCursor_OMPTeamsDistributeParallelForDirective = 274; + + /// OpenMP target teams directive. static const int CXCursor_OMPTargetTeamsDirective = 275; + + /// OpenMP target teams distribute directive. static const int CXCursor_OMPTargetTeamsDistributeDirective = 276; + + /// OpenMP target teams distribute parallel for directive. static const int CXCursor_OMPTargetTeamsDistributeParallelForDirective = 277; + + /// OpenMP target teams distribute parallel for simd directive. static const int CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective = 278; + + /// OpenMP target teams distribute simd directive. static const int CXCursor_OMPTargetTeamsDistributeSimdDirective = 279; + + /// C++2a std::bit_cast expression. static const int CXCursor_BuiltinBitCastExpr = 280; + + /// OpenMP master taskloop directive. static const int CXCursor_OMPMasterTaskLoopDirective = 281; + + /// OpenMP parallel master taskloop directive. static const int CXCursor_OMPParallelMasterTaskLoopDirective = 282; + + /// OpenMP master taskloop simd directive. static const int CXCursor_OMPMasterTaskLoopSimdDirective = 283; + + /// OpenMP parallel master taskloop simd directive. static const int CXCursor_OMPParallelMasterTaskLoopSimdDirective = 284; + + /// OpenMP parallel master directive. static const int CXCursor_OMPParallelMasterDirective = 285; static const int CXCursor_LastStmt = 285; + + /// Cursor that represents the translation unit itself. static const int CXCursor_TranslationUnit = 300; static const int CXCursor_FirstAttr = 400; + + /// An attribute whose specific kind is not exposed via this interface. static const int CXCursor_UnexposedAttr = 400; static const int CXCursor_IBActionAttr = 401; static const int CXCursor_IBOutletAttr = 402; @@ -338,22 +726,43 @@ class CXCursorKind { static const int CXCursor_InclusionDirective = 503; static const int CXCursor_FirstPreprocessing = 500; static const int CXCursor_LastPreprocessing = 503; + + /// A module import declaration. static const int CXCursor_ModuleImportDecl = 600; static const int CXCursor_TypeAliasTemplateDecl = 601; + + /// A static_assert or _Static_assert node static const int CXCursor_StaticAssert = 602; + + /// a friend declaration. static const int CXCursor_FriendDecl = 603; static const int CXCursor_FirstExtraDecl = 600; static const int CXCursor_LastExtraDecl = 603; + + /// A code completion overload candidate. static const int CXCursor_OverloadCandidate = 700; } /// Options to control the display of diagnostics. class CXDiagnosticDisplayOptions { + /// Display the source-location information where the diagnostic was located. static const int CXDiagnostic_DisplaySourceLocation = 1; + + /// If displaying the source-location information of the diagnostic, also + /// include the column number. static const int CXDiagnostic_DisplayColumn = 2; + + /// If displaying the source-location information of the diagnostic, also + /// include information about source ranges in a machine-parsable format. static const int CXDiagnostic_DisplaySourceRanges = 4; + + /// Display the option name associated with this diagnostic, if any. static const int CXDiagnostic_DisplayOption = 8; + + /// Display the category number associated with this diagnostic, if any. static const int CXDiagnostic_DisplayCategoryId = 16; + + /// Display the category name associated with this diagnostic, if any. static const int CXDiagnostic_DisplayCategoryName = 32; } @@ -418,6 +827,70 @@ class _ArrayHelper_CXSourceLocation_ptr_data { } } +/// Identifies a half-open character range in the source code. +class CXSourceRange extends ffi.Struct { + ffi.Pointer _ptr_data_item_0; + ffi.Pointer _ptr_data_item_1; + ffi.Pointer _ptr_data_item_2; + + /// helper for array, supports `[]` operator + _ArrayHelper_CXSourceRange_ptr_data get ptr_data => + _ArrayHelper_CXSourceRange_ptr_data(this, 3); + @ffi.Uint32() + int begin_int_data; + + @ffi.Uint32() + int end_int_data; +} + +/// Helper for array ptr_data in struct CXSourceRange +class _ArrayHelper_CXSourceRange_ptr_data { + final CXSourceRange _struct; + final int length; + _ArrayHelper_CXSourceRange_ptr_data(this._struct, this.length); + void operator []=(int index, ffi.Pointer value) { + switch (index) { + case 0: + _struct._ptr_data_item_0 = value; + break; + case 1: + _struct._ptr_data_item_1 = value; + break; + case 2: + _struct._ptr_data_item_2 = value; + break; + default: + throw RangeError('Index $index must be in the range [0..2].'); + } + } + + ffi.Pointer operator [](int index) { + switch (index) { + case 0: + return _struct._ptr_data_item_0; + case 1: + return _struct._ptr_data_item_1; + case 2: + return _struct._ptr_data_item_2; + default: + throw RangeError('Index $index must be in the range [0..2].'); + } + } + + @override + String toString() { + if (length == 0) return '[]'; + final sb = StringBuffer('['); + sb.write(this[0]); + for (var i = 1; i < length; i++) { + sb.write(','); + sb.write(this[i]); + } + sb.write(']'); + return sb.toString(); + } +} + /// A character string. class CXString extends ffi.Struct { ffi.Pointer data; @@ -430,22 +903,65 @@ class CXTranslationUnitImpl extends ffi.Struct {} /// Flags that control the creation of translation units. class CXTranslationUnit_Flags { + /// Used to indicate that no special translation-unit options are needed. static const int CXTranslationUnit_None = 0; + + /// Used to indicate that the parser should construct a "detailed" + /// preprocessing record, including all macro definitions and instantiations. static const int CXTranslationUnit_DetailedPreprocessingRecord = 1; + + /// Used to indicate that the translation unit is incomplete. static const int CXTranslationUnit_Incomplete = 2; + + /// Used to indicate that the translation unit should be built with an + /// implicit precompiled header for the preamble. static const int CXTranslationUnit_PrecompiledPreamble = 4; + + /// Used to indicate that the translation unit should cache some + /// code-completion results with each reparse of the source file. static const int CXTranslationUnit_CacheCompletionResults = 8; + + /// Used to indicate that the translation unit will be serialized with + /// clang_saveTranslationUnit. static const int CXTranslationUnit_ForSerialization = 16; + + /// DEPRECATED: Enabled chained precompiled preambles in C++. static const int CXTranslationUnit_CXXChainedPCH = 32; + + /// Used to indicate that function/method bodies should be skipped while + /// parsing. static const int CXTranslationUnit_SkipFunctionBodies = 64; + + /// Used to indicate that brief documentation comments should be included into + /// the set of code completions returned from this translation unit. static const int CXTranslationUnit_IncludeBriefCommentsInCodeCompletion = 128; + + /// Used to indicate that the precompiled preamble should be created on the + /// first parse. Otherwise it will be created on the first reparse. This + /// trades runtime on the first parse (serializing the preamble takes time) + /// for reduced runtime on the second parse (can now reuse the preamble). static const int CXTranslationUnit_CreatePreambleOnFirstParse = 256; + + /// Do not stop processing when fatal errors are encountered. static const int CXTranslationUnit_KeepGoing = 512; + + /// Sets the preprocessor in a mode for parsing a single file only. static const int CXTranslationUnit_SingleFileParse = 1024; + + /// Used in combination with CXTranslationUnit_SkipFunctionBodies to constrain + /// the skipping of function bodies to the preamble. static const int CXTranslationUnit_LimitSkipFunctionBodiesToPreamble = 2048; + + /// Used to indicate that attributed types should be included in CXType. static const int CXTranslationUnit_IncludeAttributedTypes = 4096; + + /// Used to indicate that implicit attributes should be visited. static const int CXTranslationUnit_VisitImplicitAttributes = 8192; + + /// Used to indicate that non-errors from included files should be ignored. static const int CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles = 16384; + + /// Tells the preprocessor not to skip excluded conditional blocks. static const int CXTranslationUnit_RetainExcludedConditionalBlocks = 32768; } @@ -512,7 +1028,10 @@ class _ArrayHelper_CXType_data { /// Describes the kind of type class CXTypeKind { + /// Represents an invalid type (e.g., where no type is available). static const int CXType_Invalid = 0; + + /// A type whose specific kind is not exposed via this interface. static const int CXType_Unexposed = 1; static const int CXType_Void = 2; static const int CXType_Bool = 3; @@ -572,6 +1091,8 @@ class CXTypeKind { static const int CXType_DependentSizedArray = 116; static const int CXType_MemberPointer = 117; static const int CXType_Auto = 118; + + /// Represents a type that was referred to using an elaborated type keyword. static const int CXType_Elaborated = 119; static const int CXType_Pipe = 120; static const int CXType_OCLImage1dRO = 121; @@ -634,10 +1155,13 @@ class CXTypeKind { /// Provides the contents of a file that has not yet been saved to disk. class CXUnsavedFile extends ffi.Struct { + /// The file whose contents have not yet been saved. ffi.Pointer Filename; + /// A buffer containing the unsaved contents of this file. ffi.Pointer Contents; + /// The length of the unsaved contents of this buffer. @ffi.Uint64() int Length; } @@ -697,6 +1221,31 @@ typedef _dart_clang_Cursor_getBriefCommentText_wrap = ffi.Pointer ffi.Pointer cursor, ); +/// Returns the comment range. +ffi.Pointer clang_Cursor_getCommentRange_wrap( + ffi.Pointer cursor, +) { + return _clang_Cursor_getCommentRange_wrap( + cursor, + ); +} + +final _dart_clang_Cursor_getCommentRange_wrap + _clang_Cursor_getCommentRange_wrap = _dylib.lookupFunction< + _c_clang_Cursor_getCommentRange_wrap, + _dart_clang_Cursor_getCommentRange_wrap>( + 'clang_Cursor_getCommentRange_wrap'); + +typedef _c_clang_Cursor_getCommentRange_wrap = ffi.Pointer + Function( + ffi.Pointer cursor, +); + +typedef _dart_clang_Cursor_getCommentRange_wrap = ffi.Pointer + Function( + ffi.Pointer cursor, +); + int clang_Cursor_getNumArguments_wrap( ffi.Pointer cursor, ) { @@ -719,6 +1268,30 @@ typedef _dart_clang_Cursor_getNumArguments_wrap = int Function( ffi.Pointer cursor, ); +/// Returns the raw comment. +ffi.Pointer clang_Cursor_getRawCommentText_wrap( + ffi.Pointer cursor, +) { + return _clang_Cursor_getRawCommentText_wrap( + cursor, + ); +} + +final _dart_clang_Cursor_getRawCommentText_wrap + _clang_Cursor_getRawCommentText_wrap = _dylib.lookupFunction< + _c_clang_Cursor_getRawCommentText_wrap, + _dart_clang_Cursor_getRawCommentText_wrap>( + 'clang_Cursor_getRawCommentText_wrap'); + +typedef _c_clang_Cursor_getRawCommentText_wrap = ffi.Pointer Function( + ffi.Pointer cursor, +); + +typedef _dart_clang_Cursor_getRawCommentText_wrap = ffi.Pointer + Function( + ffi.Pointer cursor, +); + ffi.Pointer clang_Type_getNamedType_wrap( ffi.Pointer elaboratedType, ) { @@ -847,6 +1420,31 @@ typedef _dart_clang_disposeTranslationUnit = void Function( ffi.Pointer arg0, ); +/// Returns non-zero if the ranges are the same, zero if they differ. +int clang_equalRanges_wrap( + ffi.Pointer c1, + ffi.Pointer c2, +) { + return _clang_equalRanges_wrap( + c1, + c2, + ); +} + +final _dart_clang_equalRanges_wrap _clang_equalRanges_wrap = _dylib + .lookupFunction<_c_clang_equalRanges_wrap, _dart_clang_equalRanges_wrap>( + 'clang_equalRanges_wrap'); + +typedef _c_clang_equalRanges_wrap = ffi.Uint32 Function( + ffi.Pointer c1, + ffi.Pointer c2, +); + +typedef _dart_clang_equalRanges_wrap = int Function( + ffi.Pointer c1, + ffi.Pointer c2, +); + ffi.Pointer clang_formatDiagnostic_wrap( ffi.Pointer diag, int opts, @@ -1370,7 +1968,9 @@ typedef _dart_clang_getTypedefDeclUnderlyingType_wrap = ffi.Pointer ffi.Pointer cxcursor, ); -/// Same as clang_parseTranslationUnit2, but returns the CXTranslationUnit instead of an error code. In case of an error this routine returns a NULL CXTranslationUnit, without further detailed error codes. +/// Same as clang_parseTranslationUnit2, but returns the CXTranslationUnit +/// instead of an error code. In case of an error this routine returns a NULL +/// CXTranslationUnit, without further detailed error codes. ffi.Pointer clang_parseTranslationUnit( ffi.Pointer CIdx, ffi.Pointer source_filename, @@ -1417,7 +2017,8 @@ typedef _dart_clang_parseTranslationUnit = ffi.Pointer int options, ); -/// Visitor is a function pointer with parameters having pointers to cxcursor instead of cxcursor by default. +/// Visitor is a function pointer with parameters having pointers to cxcursor +/// instead of cxcursor by default. int clang_visitChildren_wrap( ffi.Pointer parent, ffi.Pointer> _modifiedVisitor, diff --git a/lib/src/header_parser/sub_parsers/enumdecl_parser.dart b/lib/src/header_parser/sub_parsers/enumdecl_parser.dart index 19fd1ced..c3e5a545 100644 --- a/lib/src/header_parser/sub_parsers/enumdecl_parser.dart +++ b/lib/src/header_parser/sub_parsers/enumdecl_parser.dart @@ -80,8 +80,10 @@ int _enumCursorVisitor(Pointer cursor, void _addEnumConstantToEnumClass(Pointer cursor) { _enumClass.enumConstants.add( EnumConstant( - // Extracting doc comment doesn't always give the right comment - // so we are skipping dartdoc for individual enum constants. + dartDoc: getCursorDocComment( + cursor, + nesting.length + commentPrefix.length, + ), name: cursor.spelling(), value: clang.clang_getEnumConstantDeclValue_wrap(cursor)), ); diff --git a/lib/src/header_parser/sub_parsers/structdecl_parser.dart b/lib/src/header_parser/sub_parsers/structdecl_parser.dart index 27d8efdd..0c9dfa33 100644 --- a/lib/src/header_parser/sub_parsers/structdecl_parser.dart +++ b/lib/src/header_parser/sub_parsers/structdecl_parser.dart @@ -113,6 +113,10 @@ int _structMembersVisitor(Pointer cursor, _members.add( Member( + dartDoc: getCursorDocComment( + cursor, + nesting.length + commentPrefix.length, + ), name: cursor.spelling(), type: mt, ), diff --git a/lib/src/header_parser/utils.dart b/lib/src/header_parser/utils.dart index 254a9505..fbc4d316 100644 --- a/lib/src/header_parser/utils.dart +++ b/lib/src/header_parser/utils.dart @@ -8,6 +8,7 @@ import 'package:ffi/ffi.dart'; import 'package:ffigen/src/code_generator.dart'; import 'package:logging/logging.dart'; +import '../strings.dart' as strings; import 'clang_bindings/clang_bindings.dart' as clang; import 'data.dart'; import 'type_extractor/extractor.dart'; @@ -47,6 +48,12 @@ void logTuDiagnostics( } } +extension CXSourceRangeExt on Pointer { + void dispose() { + free(this); + } +} + extension CXCursorExt on Pointer { /// Returns the kind int from [clang.CXCursorKind]. int kind() { @@ -113,11 +120,98 @@ extension CXCursorExt on Pointer { } } -// TODO(13): Improve generated doc comment. -String getCursorDocComment(Pointer cursor) { - return config.extractComments - ? clang.clang_Cursor_getBriefCommentText_wrap(cursor).toStringAndDispose() - : null; +const commentPrefix = '/// '; +const nesting = ' '; + +/// Stores the [clang.CXSourceRange] of the last comment. +Pointer lastCommentRange = nullptr; + +/// Returns a cursor's associated comment. +/// +/// The given string is wrapped at line width = 80 - [indent]. The [indent] is +/// [commentPrefix.length] by default because a comment starts with +/// [commentPrefix]. +String getCursorDocComment(Pointer cursor, + [int indent = commentPrefix.length]) { + String formattedDocComment; + final currentCommentRange = clang.clang_Cursor_getCommentRange_wrap(cursor); + + // See if this comment and the last comment both point to the same source + // range. + if (lastCommentRange != nullptr && + currentCommentRange != nullptr && + clang.clang_equalRanges_wrap(lastCommentRange, currentCommentRange) != + 0) { + formattedDocComment = null; + } else { + switch (config.comment) { + case strings.full: + formattedDocComment = removeRawCommentMarkups(clang + .clang_Cursor_getRawCommentText_wrap(cursor) + .toStringAndDispose()); + break; + case strings.brief: + formattedDocComment = _wrapNoNewLineString( + clang + .clang_Cursor_getBriefCommentText_wrap(cursor) + .toStringAndDispose(), + 80 - indent); + break; + default: + formattedDocComment = null; + } + } + lastCommentRange.dispose(); + lastCommentRange = currentCommentRange; + return formattedDocComment; +} + +/// Wraps [string] according to given [lineWidth]. +/// +/// Wrapping will work properly only when String has no new lines +/// characters(\n). +String _wrapNoNewLineString(String string, int lineWidth) { + if (string == null || string.isEmpty) { + return null; + } + final sb = StringBuffer(); + + final words = string.split(' '); + + sb.write(words[0]); + int trackLineWidth = words[0].length; + for (var i = 1; i < words.length; i++) { + final word = words[i]; + if (trackLineWidth + word.length < lineWidth) { + sb.write(' '); + sb.write(word); + trackLineWidth += word.length + 1; + } else { + sb.write('\n'); + sb.write(word); + trackLineWidth = word.length; + } + } + return sb.toString(); +} + +/// Removes /*, */ and any *'s in the beginning of a line. +String removeRawCommentMarkups(String string) { + if (string == null || string.isEmpty) { + return null; + } + final sb = StringBuffer(); + + // Remove comment identifiers. + string = string.replaceAll('/*', ''); + string = string.replaceAll('*/', ''); + + // Remove any *'s in the beginning of a every line. + string.split('\n').forEach((element) { + element = element.trim().replaceFirst(RegExp(r'\**'), '').trim(); + sb.writeln(element); + }); + return sb.toString().trim(); } extension CXTypeExt on Pointer { diff --git a/lib/src/strings.dart b/lib/src/strings.dart index 9d9ff17a..e96ddc13 100644 --- a/lib/src/strings.dart +++ b/lib/src/strings.dart @@ -58,7 +58,14 @@ const sizemap_native_mapping = { const sort = 'sort'; const useSupportedTypedefs = 'use-supported-typedefs'; const warnWhenRemoving = 'warn-when-removing'; -const extractComments = 'extract-comments'; + +const comments = 'comments'; +// Comment type. +const brief = 'brief'; +const full = 'full'; +const none = 'none'; +// Contains all possibe comment types. +const commentTypeSet = {brief, full, none}; // Dynamic library names. const libclang_dylib_linux = 'libwrapped_clang.so'; diff --git a/tool/libclang_config.yaml b/tool/libclang_config.yaml index 575a4400..bac4935b 100644 --- a/tool/libclang_config.yaml +++ b/tool/libclang_config.yaml @@ -35,6 +35,11 @@ structs: names: - CXCursor - CXType + - CXSourceLocation + - CXString + - CXTranslationUnitImpl + - CXUnsavedFile + - CXSourceRange functions: include: @@ -68,6 +73,9 @@ functions: - clang_getNumArgTypes_wrap - clang_getArgType_wrap - clang_getEnumConstantDeclValue_wrap + - clang_equalRanges_wrap + - clang_Cursor_getCommentRange_wrap + - clang_Cursor_getRawCommentText_wrap - clang_Cursor_getBriefCommentText_wrap - clang_getCursorLocation_wrap - clang_getFileLocation_wrap diff --git a/tool/wrapped_libclang/wrapper.c b/tool/wrapped_libclang/wrapper.c index 2e0e375c..aa1e94da 100644 --- a/tool/wrapped_libclang/wrapper.c +++ b/tool/wrapped_libclang/wrapper.c @@ -32,6 +32,12 @@ CXSourceLocation *ptrToCXSourceLocation(CXSourceLocation t) *c = t; return c; } +CXSourceRange *ptrToCXSourceRange(CXSourceRange t) +{ + CXSourceRange *c = aloc(CXSourceRange); + *c = t; + return c; +} // START ===== Functions for testing libclang behavior in C. enum CXChildVisitResult visitor_for_test_in_c(CXCursor cursor, CXCursor parent, CXClientData clientData) { @@ -240,6 +246,24 @@ long long clang_getEnumConstantDeclValue_wrap(CXCursor *cursor) return clang_getEnumConstantDeclValue(*cursor); } +/** Returns non-zero if the ranges are the same, zero if they differ. */ +unsigned clang_equalRanges_wrap(CXSourceRange *c1, CXSourceRange *c2) +{ + return clang_equalRanges(*c1, *c2); +} + +/** Returns the comment range. */ +CXSourceRange *clang_Cursor_getCommentRange_wrap(CXCursor *cursor) +{ + return ptrToCXSourceRange(clang_Cursor_getCommentRange(*cursor)); +} + +/** Returns the raw comment. */ +CXString *clang_Cursor_getRawCommentText_wrap(CXCursor *cursor) +{ + return ptrToCXString(clang_Cursor_getRawCommentText(*cursor)); +} + /** Returns the first paragraph of doxygen doc comment. */ CXString *clang_Cursor_getBriefCommentText_wrap(CXCursor *cursor) { diff --git a/tool/wrapped_libclang/wrapper.def b/tool/wrapped_libclang/wrapper.def index 36902ae7..5a10727e 100644 --- a/tool/wrapped_libclang/wrapper.def +++ b/tool/wrapped_libclang/wrapper.def @@ -344,6 +344,9 @@ clang_Cursor_getArgument_wrap clang_getNumArgTypes_wrap clang_getArgType_wrap clang_getEnumConstantDeclValue_wrap +clang_equalRanges_wrap +clang_Cursor_getCommentRange_wrap +clang_Cursor_getRawCommentText_wrap clang_Cursor_getBriefCommentText_wrap clang_getCursorLocation_wrap clang_getFileLocation_wrap