Skip to content

Commit

Permalink
Fix crash when accessing property TemplateTypeParmDecl.DefaultArgument
Browse files Browse the repository at this point in the history
* hasDefaultArgType() must be called first.
* Since the type may not have a default arg type, make the property nullable.
  • Loading branch information
ceresgalax committed Feb 11, 2024
1 parent b9479d2 commit 716ae31
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
10 changes: 7 additions & 3 deletions sources/ClangSharp/Cursors/Decls/TemplateTypeParmDecl.cs
Expand Up @@ -5,13 +5,14 @@
using ClangSharp.Interop;
using static ClangSharp.Interop.CXCursorKind;
using static ClangSharp.Interop.CX_DeclKind;
using static ClangSharp.Interop.CXTypeKind;

namespace ClangSharp;

public sealed class TemplateTypeParmDecl : TypeDecl
{
private readonly Lazy<IReadOnlyList<Expr>> _associatedConstraints;
private readonly Lazy<Type> _defaultArgument;
private readonly Lazy<Type?> _defaultArgument;

internal TemplateTypeParmDecl(CXCursor handle) : base(handle, CXCursor_TemplateTypeParameter, CX_DeclKind_TemplateTypeParm)
{
Expand All @@ -27,12 +28,15 @@ internal TemplateTypeParmDecl(CXCursor handle) : base(handle, CXCursor_TemplateT
return associatedConstraints;
});
_defaultArgument = new Lazy<Type>(() => TranslationUnit.GetOrCreate<Type>(Handle.DefaultArgType));
_defaultArgument = new Lazy<Type?>(() => {
CXType defaultArgType = Handle.DefaultArgType;
return defaultArgType.kind == CXType_Invalid ? null : TranslationUnit.GetOrCreate<Type>(defaultArgType);
});
}

public IReadOnlyList<Expr> AssociatedConstraints => _associatedConstraints.Value;

public Type DefaultArgument => _defaultArgument.Value;
public Type? DefaultArgument => _defaultArgument.Value;

public bool DefaultArgumentWasInherited => Handle.HasInheritedDefaultArg;

Expand Down
8 changes: 6 additions & 2 deletions sources/libClangSharp/ClangSharp.cpp
Expand Up @@ -1001,15 +1001,19 @@ CXCursor clangsharp_Cursor_getDefaultArg(CXCursor C) {
}

CXType clangsharp_Cursor_getDefaultArgType(CXCursor C) {
QualType QT;

if (isDeclOrTU(C.kind)) {
const Decl* D = getCursorDecl(C);

if (const TemplateTypeParmDecl* TTPD = dyn_cast<TemplateTypeParmDecl>(D)) {
return MakeCXType(TTPD->getDefaultArgument(), getCursorTU(C));
if (TTPD->hasDefaultArgument()) {
QT = TTPD->getDefaultArgument();
}
}
}

return MakeCXType(QualType(), getCursorTU(C));
return MakeCXType(QT, getCursorTU(C));
}

CXCursor clangsharp_Cursor_getDefinition(CXCursor C) {
Expand Down

0 comments on commit 716ae31

Please sign in to comment.