Skip to content

go/build: support language-specific go:build comment prefixes for non-Go files#14

Open
hbrooks wants to merge 1 commit into
masterfrom
demo/pr-79537
Open

go/build: support language-specific go:build comment prefixes for non-Go files#14
hbrooks wants to merge 1 commit into
masterfrom
demo/pr-79537

Conversation

@hbrooks
Copy link
Copy Markdown

@hbrooks hbrooks commented May 28, 2026

…-Go files

Files in languages other than Go that happen to share an extension
recognised by the Go toolchain (most notably MATLAB .m files, which
Go treats as Objective-C) cannot currently carry go:build constraints
using their native comment syntax.  The only workaround is to add a
//go:build line at the top of the file, but that line is a syntax
error in MATLAB (and other languages), causing those tools to reject
the file.

This change teaches the build system to recognise language-specific
line-comment prefixes for go:build directives in non-Go source files:

  Extension  Prefix        Language
  .m         % go:build    MATLAB
  .f90       ! go:build    Fortran (free-form)

A MATLAB file can now opt out of the build with:

  % go:build ignore

and MATLAB itself will continue to parse the file normally, because
the line is a valid MATLAB comment.

Implementation
--------------
* go/build/build.go
  - extCommentPrefix: map[string][]byte of extension → comment prefix
  - goBuildCommentForExt: helper to look up the prefix
  - isGoBuildCommentWithPrefix: generalised isGoBuildComment
  - parseFileHeaderWithPrefix: like parseFileHeader but for single-
    line comment syntaxes (no /* */ block-comment tracking needed)
  - shouldBuildWithPrefix: shouldBuild extended with an optional
    commentPrefix parameter; shouldBuild delegates to it with nil
  - matchFile: passes the appropriate commentPrefix for non-Go files

* cmd/go/internal/modindex/build.go
  Same changes mirrored in the module-index copy of the logic:
  getConstraintsWithPrefix, parseFileHeaderWithPrefix,
  isGoBuildCommentWithPrefix, extCommentPrefix.

Tests
-----
* TestShouldBuildWithPrefix  – unit tests for % go:build and # go:build
* TestMatlabFileBuildTags    – ImportDir integration test using real
  testdata .m files (ignored.m, included.m, linux_only.m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant