Skip to content

Commit e1e43fd

Browse files
authored
Unparse comment references using AST tokens (#2642)
* Unparse comment references via tokens instead of file access * dartfmt * Rewording
1 parent e6a9b7c commit e1e43fd

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

lib/src/comment_references/model_comment_reference.dart

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import 'package:analyzer/dart/ast/ast.dart';
66
import 'package:analyzer/dart/element/element.dart';
77
import 'package:analyzer/file_system/file_system.dart';
88
import 'package:dartdoc/src/comment_references/parser.dart';
9-
import 'package:dartdoc/src/model_utils.dart';
109

1110
abstract class ModelCommentReference {
1211
/// Does the structure of the reference itself imply a possible default
@@ -70,9 +69,15 @@ class _ModelCommentReferenceImpl implements ModelCommentReference {
7069
/// [CommentReference].
7170
static String _referenceText(
7271
CommentReference ref, ResourceProvider resourceProvider) {
73-
var contents = getFileContentsFor(
74-
(ref.root as CompilationUnit).declaredElement, resourceProvider);
75-
return contents.substring(ref.offset, ref.end);
72+
var token = (ref.parent as Comment)
73+
.tokens
74+
.firstWhere((t) => t.offset <= ref.offset && t.end >= ref.end);
75+
// This is a little sketchy, but works since comments happen to be a token
76+
// that is fully preserved in its string representation.
77+
// TODO(jcollins-g): replace unparsing in general with lower level changes.
78+
return token
79+
.toString()
80+
.substring(ref.offset - token.offset, ref.end - token.offset);
7681
}
7782

7883
List<CommentReferenceNode> _parsed;

lib/src/model_utils.dart

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,12 @@ Iterable<Class> findCanonicalFor(Iterable<Class> classes) {
9696
c.packageGraph.findCanonicalModelElementFor(c.element) as Class ?? c);
9797
}
9898

99+
/// Uses direct file access to get the contents of a file. Cached.
100+
///
101+
/// Direct reading of source code via a [PhysicalResourceProvider] is not
102+
/// allowed in some environments, so avoid using this.
103+
// TODO(jcollins-g): consider deprecating this and the `--include-source`
104+
// feature that uses it now that source code linking is possible.
99105
String getFileContentsFor(Element e, ResourceProvider resourceProvider) {
100106
var location = e.source.fullName;
101107
if (!_fileContents.containsKey(location)) {

0 commit comments

Comments
 (0)