Skip to content

Commit

Permalink
Unparse comment references using AST tokens (#2642)
Browse files Browse the repository at this point in the history
* Unparse comment references via tokens instead of file access

* dartfmt

* Rewording
  • Loading branch information
jcollins-g committed May 12, 2021
1 parent e6a9b7c commit e1e43fd
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
13 changes: 9 additions & 4 deletions lib/src/comment_references/model_comment_reference.dart
Expand Up @@ -6,7 +6,6 @@ import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:dartdoc/src/comment_references/parser.dart';
import 'package:dartdoc/src/model_utils.dart';

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

List<CommentReferenceNode> _parsed;
Expand Down
6 changes: 6 additions & 0 deletions lib/src/model_utils.dart
Expand Up @@ -96,6 +96,12 @@ Iterable<Class> findCanonicalFor(Iterable<Class> classes) {
c.packageGraph.findCanonicalModelElementFor(c.element) as Class ?? c);
}

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

0 comments on commit e1e43fd

Please sign in to comment.