tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Build C, C++, Objective-C and Zig from C# project files
- Commit
b3f7192ee1f8aabcb2001c639f73a7e4ad1e9ed0- Author
- Leitwolf11 ·
- Parents
e8313e4274d8
Changes
.editorconfig | 18 + .github/renovate.json5 | 32 ++ .github/workflows/ci.yml | 100 +++++ .github/workflows/codeql.yml | 59 +++ .github/workflows/dependency-review.yml | 34 ++ .github/workflows/fuzzing.yml | 74 ++++ .github/workflows/zizmor.yml | 38 ++ .gitignore | 14 + CHANGELOG.md | 20 + Directory.Build.props | 24 ++ Directory.Packages.props | 21 ++ LICENSES/0BSD.txt | 14 + LICENSES/Apache-2.0.txt | 177 +++++++++ README.md | 57 +++ THIRD-PARTY-NOTICES.md | 17 + Tazel.slnx | 15 + .../Progmasoft.Tazel.Benchmarks/Benchmarks.cs | 60 +++ .../Progmasoft.Tazel.Benchmarks.csproj | 15 + docs/README.md | 14 + docs/architecture.md | 51 +++ docs/commands.md | 95 +++++ docs/development.md | 59 +++ docs/project-files.md | 251 +++++++++++++ docs/reference/.gitignore | 1 + docs/reference/docfx.json | 15 + docs/reference/index.md | 8 + docs/reference/toc.yml | 4 + dotnet-tools.json | 20 + .../Progmasoft.Tazel.Fuzz.csproj | 14 + fuzz/Progmasoft.Tazel.Fuzz/Program.cs | 68 ++++ fuzz/corpus/command-line/build | 4 + fuzz/corpus/custom/notes.txt | 65 ++++ fuzz/corpus/depfile/one | 2 + fuzz/corpus/label/pattern | 1 + fuzz/corpus/label/target | 1 + fuzz/corpus/options/notes.txt | 13 + global.json | 10 + .../Build/Prelude/CCSettings.cs | 197 ++++++++++ src/Progmasoft.Tazel.Dsl/Build/Prelude/Families.cs | 134 +++++++ .../Build/Prelude/ObjectiveCSettings.cs | 126 +++++++ .../Build/Prelude/ZigSettings.cs | 131 +++++++ .../Build/Toolchain/Prelude/Toolchains.cs | 164 +++++++++ src/Progmasoft.Tazel.Dsl/Common/Files.cs | 117 ++++++ src/Progmasoft.Tazel.Dsl/Common/Platform.cs | 149 ++++++++ src/Progmasoft.Tazel.Dsl/Common/References.cs | 106 ++++++ src/Progmasoft.Tazel.Dsl/Declarations.cs | 150 ++++++++ .../Module/Prelude/ModuleDsl.cs | 364 ++++++++++++++++++ .../Module/Prelude/TazelVersion.cs | 125 +++++++ .../Progmasoft.Tazel.Dsl.csproj | 12 + src/Progmasoft.Tazel/Archive/ModuleArchive.cs | 293 +++++++++++++++ src/Progmasoft.Tazel/Cli/CommandLine.cs | 406 +++++++++++++++++++++ src/Progmasoft.Tazel/Cli/Commands.cs | 290 +++++++++++++++ src/Progmasoft.Tazel/Cli/Help.cs | 120 ++++++ src/Progmasoft.Tazel/Cli/Selector.cs | 169 +++++++++ src/Progmasoft.Tazel/Cli/Suggestions.cs | 53 +++ src/Progmasoft.Tazel/Driver/Actions.cs | 282 ++++++++++++++ src/Progmasoft.Tazel/Driver/BuildOptions.cs | 65 ++++ src/Progmasoft.Tazel/Driver/CCPlanner.cs | 384 +++++++++++++++++++ src/Progmasoft.Tazel/Driver/Executor.cs | 130 +++++++ src/Progmasoft.Tazel/Driver/Planner.cs | 251 +++++++++++++ src/Progmasoft.Tazel/Driver/Processes.cs | 177 +++++++++ src/Progmasoft.Tazel/Driver/TestRunner.cs | 204 +++++++++++ src/Progmasoft.Tazel/Driver/Toolchains.cs | 262 +++++++++++++ src/Progmasoft.Tazel/Driver/ZigPlanner.cs | 315 ++++++++++++++++ src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs | 129 +++++++ .../Dsl/Custom/Lexer/CustomLexer.cs | 226 ++++++++++++ .../Dsl/Custom/Parser/CustomParser.cs | 150 ++++++++ src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs | 261 +++++++++++++ src/Progmasoft.Tazel/Label/Labels.cs | 179 +++++++++ src/Progmasoft.Tazel/Output/Reporter.cs | 205 +++++++++++ src/Progmasoft.Tazel/Progmasoft.Tazel.csproj | 26 ++ src/Progmasoft.Tazel/Program.cs | 70 ++++ src/Progmasoft.Tazel/Project/FileSets.cs | 198 ++++++++++ src/Progmasoft.Tazel/Project/LocalModules.cs | 101 +++++ src/Progmasoft.Tazel/Project/ModuleFiles.cs | 76 ++++ src/Progmasoft.Tazel/Project/ScriptHost.cs | 143 ++++++++ src/Progmasoft.Tazel/Project/TargetChecks.cs | 69 ++++ src/Progmasoft.Tazel/Project/Workspace.cs | 378 +++++++++++++++++++ tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs | 182 +++++++++ tests/Progmasoft.Tazel.Tests/CommandLineTests.cs | 119 ++++++ tests/Progmasoft.Tazel.Tests/FileTests.cs | 154 ++++++++ tests/Progmasoft.Tazel.Tests/LabelTests.cs | 72 ++++ tests/Progmasoft.Tazel.Tests/PlannerTests.cs | 178 +++++++++ .../Progmasoft.Tazel.Tests.csproj | 20 + tests/Progmasoft.Tazel.Tests/SnapshotTests.cs | 36 ++ tests/Progmasoft.Tazel.Tests/Snapshots.cs | 155 ++++++++ tests/Progmasoft.Tazel.Tests/TemporaryModule.cs | 64 ++++ tests/Progmasoft.Tazel.Tests/TextFileTests.cs | 134 +++++++ tests/Progmasoft.Tazel.Tests/WorkspaceTests.cs | 127 +++++++ .../PlannerTests.TheCommandsOfABuild.snap | 211 +++++++++++ 90 files changed, 10324 insertions(+) diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..9ca8b97 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +# SPDX-License-Identifier: MIT + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{json,json5,yml,yaml,slnx,props,csproj}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/renovate.json5 b/.github/renovate.json5 new file mode 100644 index 0000000..0b69bbe --- /dev/null +++ b/.github/renovate.json5 @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +// Renovate proposes the version updates of this repository. Dependabot keeps its alerts and its security updates; +// its version updates are off, so that two bots do not open the same pull request. +{ + $schema: "https://docs.renovatebot.com/renovate-schema.json", + extends: ["config:recommended", "helpers:pinGitHubActionDigests"], + + timezone: "Europe/Istanbul", + // Once a week, before the working day. + schedule: ["before 6am on monday"], + + // A release is taken a week after it is published: one that turns out to be broken or malicious is usually + // withdrawn within days. + minimumReleaseAge: "7 days", + + rebaseWhen: "conflicted", + prConcurrentLimit: 2, + prHourlyLimit: 2, + dependencyDashboard: true, + vulnerabilityAlerts: { enabled: false }, + + enabledManagers: ["github-actions", "nuget"], + + packageRules: [ + { matchManagers: ["github-actions"], groupName: "GitHub Actions" }, + { matchManagers: ["nuget"], groupName: "NuGet packages and tools" }, + // Stable versions only. + { matchManagers: ["nuget"], ignoreUnstable: true }, + ], +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6987800 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,100 @@ +# SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +# SPDX-License-Identifier: MIT + +name: CI + +on: + pull_request: + push: + branches: + - main + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + DOTNET_NOLOGO: "1" + DOTNET_CLI_TELEMETRY_OPTOUT: "1" + # A test without its stored snapshot fails here instead of writing one. + SNAPSHOOTER_STRICT_MODE: "true" + +jobs: + test: + name: Test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + permissions: + contents: read # the checkout + id-token: write # Codecov takes the coverage with an OIDC token instead of a secret + strategy: + fail-fast: false + matrix: + os: [ubuntu-26.04, windows-2025, macos-15] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5 + with: + global-json-file: global.json + + # Zig for the Zig tests; checked against the SHA-256 that ziglang.org publishes. + - name: Install Zig + if: runner.os == 'Linux' + shell: bash + run: | + curl -fsSL -o "$RUNNER_TEMP/zig.tar.xz" https://ziglang.org/download/0.17.1/zig-x86_64-linux-0.17.1.tar.xz + echo "3581863e3cbcfd0fce0efc682ce7e9e93da96668a977791d356a26d2a7e9b17a $RUNNER_TEMP/zig.tar.xz" | sha256sum -c - + mkdir -p "$RUNNER_TEMP/zig" + tar -xJf "$RUNNER_TEMP/zig.tar.xz" -C "$RUNNER_TEMP/zig" --strip-components=1 + echo "$RUNNER_TEMP/zig" >> "$GITHUB_PATH" + + # Warnings are errors in every project (Directory.Build.props). + - name: Build + run: dotnet build Tazel.slnx -c Release + + - name: Test + run: dotnet test --solution Tazel.slnx -c Release --no-build --coverlet --coverlet-output-format cobertura --results-directory artifacts/coverage + + - name: Run the built Tazel + run: dotnet src/Progmasoft.Tazel/bin/Release/net10.0/tazel.dll version + + - name: Upload coverage + if: runner.os == 'Linux' + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + use_oidc: true + directory: artifacts/coverage + fail_ci_if_error: false + + reference: + name: DocFX + runs-on: ubuntu-26.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5 + with: + global-json-file: global.json + + # The reference of the project-file types; every DocFX warning fails it. + - name: DocFX + run: | + dotnet tool restore + dotnet docfx docs/reference/docfx.json + + - name: Keep the reference + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: tazel-reference + path: artifacts/reference/ + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..92d4d0b --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,59 @@ +# SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +# SPDX-License-Identifier: MIT + +name: CodeQL + +on: + pull_request: + push: + branches: + - main + schedule: + - cron: '23 4 * * 1' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: codeql-${{ github.ref }} + cancel-in-progress: true + +jobs: + analyze: + name: ${{ matrix.language }} + runs-on: ubuntu-26.04 + timeout-minutes: 30 + permissions: + actions: read # the analysis reads the workflow run it belongs to + contents: read # the checkout + security-events: write # the findings go to code scanning + strategy: + fail-fast: false + matrix: + language: [actions, csharp] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5 + if: matrix.language == 'csharp' + with: + global-json-file: global.json + + - name: Initialize CodeQL + uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.language == 'csharp' && 'manual' || 'none' }} + queries: security-extended + + - name: Build for extraction + if: matrix.language == 'csharp' + run: dotnet build Tazel.slnx -c Release --no-incremental + + - name: Analyze + uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + category: /language:${{ matrix.language }} diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml new file mode 100644 index 0000000..0e23eaf --- /dev/null +++ b/.github/workflows/dependency-review.yml @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +# SPDX-License-Identifier: MIT + +name: Dependency Review + +# Looks at the dependencies a pull request adds or changes, and fails when +# one of them has a known vulnerability of high severity or worse. +# Dependabot alerts report what is already there; this holds what comes in. + +on: + pull_request: + +permissions: {} + +concurrency: + group: dependency-review-${{ github.ref }} + cancel-in-progress: true + +jobs: + review: + name: Dependency review + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Review the dependency changes + uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0 + with: + fail-on-severity: high diff --git a/.github/workflows/fuzzing.yml b/.github/workflows/fuzzing.yml new file mode 100644 index 0000000..6fb61e5 --- /dev/null +++ b/.github/workflows/fuzzing.yml @@ -0,0 +1,74 @@ +# SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +# SPDX-License-Identifier: MIT + +# The readers of what users write, under libFuzzer through SharpFuzz: one minute per target on a pull request, +# thirty minutes every night. The corpus is kept in the cache, and a crashing input is kept as an artifact. +name: Fuzzing + +on: + pull_request: + schedule: + - cron: '17 2 * * *' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: fuzzing-${{ github.ref }} + cancel-in-progress: true + +jobs: + fuzz: + name: Fuzz ${{ matrix.target }} + runs-on: ubuntu-26.04 + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + target: [custom, options, label, depfile, command-line] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5 + with: + global-json-file: global.json + + - name: Build and instrument + run: | + dotnet tool restore + dotnet publish fuzz/Progmasoft.Tazel.Fuzz -c Release -o artifacts/fuzz + dotnet sharpfuzz artifacts/fuzz/tazel.dll + + - name: Install libfuzzer-dotnet + run: | + curl -fsSL -o "$RUNNER_TEMP/libfuzzer-dotnet" https://github.com/Metalnem/libfuzzer-dotnet/releases/download/v2025.05.02.0904/libfuzzer-dotnet-ubuntu + echo "c2c2a90d94c409a4af339a0d4f244e0442c5a5d249be0f1252ba07871f285958 $RUNNER_TEMP/libfuzzer-dotnet" | sha256sum -c - + chmod +x "$RUNNER_TEMP/libfuzzer-dotnet" + + - name: Restore the corpus + uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + with: + path: artifacts/corpus/${{ matrix.target }} + key: fuzz-corpus-${{ matrix.target }}-${{ github.run_id }} + restore-keys: fuzz-corpus-${{ matrix.target }}- + + - name: Fuzz + env: + TARGET: ${{ matrix.target }} + SECONDS_TO_RUN: ${{ github.event_name == 'pull_request' && '60' || '1800' }} + run: | + mkdir -p "artifacts/corpus/$TARGET" artifacts/crashes + cp -n "fuzz/corpus/$TARGET"/* "artifacts/corpus/$TARGET/" + "$RUNNER_TEMP/libfuzzer-dotnet" --target_path=artifacts/fuzz/Progmasoft.Tazel.Fuzz --target_arg="$TARGET" \ + -max_total_time="$SECONDS_TO_RUN" -timeout=10 -artifact_prefix=artifacts/crashes/ "artifacts/corpus/$TARGET" + + - name: Keep the crashing input + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: crash-${{ matrix.target }} + path: artifacts/crashes/ + retention-days: 30 diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml new file mode 100644 index 0000000..b9c1ad2 --- /dev/null +++ b/.github/workflows/zizmor.yml @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +# SPDX-License-Identifier: MIT + +name: Workflow Security + +# zizmor reads the workflows of this repository for what makes a workflow +# unsafe: a token that is wider than its job needs, text from a pull request +# that reaches a shell, an action that is not pinned. Its findings are +# uploaded to code scanning. + +on: + pull_request: + push: + branches: + - main + +permissions: {} + +concurrency: + group: zizmor-${{ github.ref }} + cancel-in-progress: true + +jobs: + zizmor: + name: zizmor + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + actions: read # the analysis reads the workflow run it belongs to + contents: read # the checkout + security-events: write # the findings go to code scanning + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Audit the workflows + uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b050abb --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +# SPDX-License-Identifier: MIT + +bin/ +obj/ +artifacts/ +TestResults/ +# Snapshooter writes what a test made here when it differs from the stored snapshot. +__mismatch__/ +*.user +.vs/ +.idea/ +# What Tazel writes when it builds a module: outputs, records of actions, unpacked dependencies. +.tazel/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ffd5f57 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,20 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# Changelog + +## Unreleased + +The first version of Tazel, written in C# for .NET 10. + +- Project files are C# scripts: `MODULE.csx` at the root of a module, `BUILD.csx` in each package, run with the C# + scripting of Roslyn. +- Targets of the families `CC`, `ObjectiveC` and `Zig`, labels as in Bazel (`//dir:x`), visibility per target, and + `TargetConstraints` that `//...` follows. +- Toolchains as in Bazel, with features of flags per action, registered in `MODULE.csx`; this machine's clang, gcc or + zig without one. +- `tazel build`, `test`, `run`, `clean`, `package`, `custom`, `version` and `help`, with `--platform`, `--mode`, + `--feature`, `--no-feature` and the options for the compilers and the linker. +- An action cache by content, depfiles for headers, parallel actions, runfiles, sharded and flaky tests. +- Reproducible `.tazel.tar.xz` archives of modules, and dependencies on them checked by SHA-256. +- `tazel_options.txt` (with `platform:`) and `tazel_custom.txt`. diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..a64771a --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,24 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<Project> + <PropertyGroup> + <TargetFramework>net10.0</TargetFramework> + <LangVersion>latest</LangVersion> + <Nullable>enable</Nullable> + <ImplicitUsings>disable</ImplicitUsings> + <TreatWarningsAsErrors>true</TreatWarningsAsErrors> + <AnalysisLevel>latest</AnalysisLevel> + <EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <Deterministic>true</Deterministic> + <ContinuousIntegrationBuild Condition="'$(CI)' == 'true'">true</ContinuousIntegrationBuild> + <InvariantGlobalization>true</InvariantGlobalization> + <Authors>Progmasoft</Authors> + <Copyright>Copyright (c) 2026 Progmasoft</Copyright> + <PackageLicenseExpression>MIT</PackageLicenseExpression> + <PackageProjectUrl>https://tazel.net</PackageProjectUrl> + <RepositoryUrl>https://github.com/Progmasoft/tazel</RepositoryUrl> + <Version>0.1.0</Version> + <IsPackable>false</IsPackable> + </PropertyGroup> +</Project> diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..aca2b46 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,21 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<!-- Every package and its version, in one place; the projects name packages without versions. --> +<Project> + <PropertyGroup> + <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> + </PropertyGroup> + <ItemGroup> + <PackageVersion Include="Spectre.Console" Version="0.57.2" /> + <PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="5.12.0" /> + <PackageVersion Include="NuGet.Versioning" Version="8.0.0" /> + <PackageVersion Include="Microsoft.Z3" Version="4.12.2" /> + <PackageVersion Include="Lzma.Net" Version="5.8.4.3" /> + <PackageVersion Include="xunit.v3" Version="4.0.3" /> + <PackageVersion Include="CsCheck" Version="5.0.1" /> + <PackageVersion Include="Snapshooter.Xunit3" Version="1.3.1" /> + <PackageVersion Include="coverlet.MTP" Version="10.1.0" /> + <PackageVersion Include="BenchmarkDotNet" Version="0.15.8" /> + <PackageVersion Include="SharpFuzz" Version="2.3.0" /> + </ItemGroup> +</Project> diff --git a/LICENSES/0BSD.txt b/LICENSES/0BSD.txt new file mode 100644 index 0000000..8445299 --- /dev/null +++ b/LICENSES/0BSD.txt @@ -0,0 +1,14 @@ +BSD Zero Clause License + +Copyright (c) 2026 Zoltan Csizmadia + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/README.md b/README.md index cc098a7..985c347 100644 --- a/README.md +++ b/README.md @@ -4,3 +4,60 @@ # Tazel Tazel is a build system and package manager for C, C++, Objective-C, Objective-C++ and Zig, written in C# for .NET 10. +A module has a `MODULE.csx` at its root and a `BUILD.csx` in each package; both are C# scripts. Targets are named by +labels, as in Bazel: `//app:greeter`, `//:math`, `@dep//:lib`. + +```cs +// BUILD.csx +using Progmasoft.Tazel.Dsl.Build.Prelude; + +var math = CC.StaticLibrary("math", new() +{ + Sources = new Glob("src/math/*.cpp"), + Headers = new Glob("include/math/*.hpp"), + IncludeDirectories = ["include"], + CppCompilerOptions = ["-std=c++23"], + Visibility = Visibility.Public +}); + +CC.Executable("greeter", new() +{ + Sources = ["src/main.cpp"], + Depends = [math], + RuntimeData = ["assets/messages.txt"] +}); + +CC.Test("math_test", new() { Sources = ["tests/math_test.cpp"], Depends = [math] }); +``` + +```text +tazel build //... +tazel run //:greeter -- --language en +tazel test //... --feature asan +tazel build //... --platform linux-aarch64 --mode release +tazel package +``` + +- **Families:** `CC` (C and C++; the language of each file comes from its extension), `ObjectiveC` (with C and C++ + files beside), and `Zig` (modules, libraries, executables and tests from a root file). +- **Toolchains** are declared as in Bazel, with features that hold flags per action, and registered in `MODULE.csx`; + without one, Tazel uses the clang, gcc or zig of this machine. +- **Builds** run each compiler command directly, many at once. An action reruns only when its command, an input or + an output changed by content. +- **Dependencies** on other modules come from their reproducible `.tazel.tar.xz` archives, checked against their + SHA-256. + +The [documentation](docs/README.md) covers the project files, the commands and how Tazel is built. + +## Building Tazel + +```text +dotnet build Tazel.slnx +dotnet test --solution Tazel.slnx +dotnet run --project src/Progmasoft.Tazel -- version +``` + +## License + +Tazel is licensed under the [MIT License](LICENSE.txt), with the [Progmasoft Patent Grant](PATENTS.md). The +libraries it ships with are listed in [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md). diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md new file mode 100644 index 0000000..5192a19 --- /dev/null +++ b/THIRD-PARTY-NOTICES.md @@ -0,0 +1,17 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# Third-party notices + +Tazel ships with the libraries below. Their licenses are in [LICENSES/](LICENSES/) and, for MIT, in +[LICENSE.txt](LICENSE.txt), whose text is the same with another copyright line. + +| Library | License | Copyright | +| --- | --- | --- | +| [Spectre.Console](https://github.com/spectreconsole/spectre.console) | MIT | Copyright (c) Patrik Svensson, Phil Scott, Nils Andresen, Cédric Luthi | +| [Roslyn](https://github.com/dotnet/roslyn): Microsoft.CodeAnalysis.CSharp.Scripting and its assemblies | MIT | Copyright (c) .NET Foundation and Contributors | +| [NuGet.Versioning](https://github.com/NuGet/NuGet.Client) | Apache-2.0 | Copyright (c) .NET Foundation and Contributors | +| [Lzma.Net](https://github.com/zcsizmadia/Lzma.Net) | 0BSD | Copyright (c) 2026 Zoltan Csizmadia | + +The libraries that only build and test Tazel (xUnit, CsCheck, Snapshooter, Coverlet, BenchmarkDotNet, SharpFuzz, +DocFX) are not part of what is shipped. diff --git a/Tazel.slnx b/Tazel.slnx new file mode 100644 index 0000000..03672ef --- /dev/null +++ b/Tazel.slnx @@ -0,0 +1,15 @@ +<Solution> + <Folder Name="/src/"> + <Project Path="src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj" /> + <Project Path="src/Progmasoft.Tazel/Progmasoft.Tazel.csproj" /> + </Folder> + <Folder Name="/tests/"> + <Project Path="tests/Progmasoft.Tazel.Tests/Progmasoft.Tazel.Tests.csproj" /> + </Folder> + <Folder Name="/benchmarks/"> + <Project Path="benchmarks/Progmasoft.Tazel.Benchmarks/Progmasoft.Tazel.Benchmarks.csproj" /> + </Folder> + <Folder Name="/fuzz/"> + <Project Path="fuzz/Progmasoft.Tazel.Fuzz/Progmasoft.Tazel.Fuzz.csproj" /> + </Folder> +</Solution> diff --git a/benchmarks/Progmasoft.Tazel.Benchmarks/Benchmarks.cs b/benchmarks/Progmasoft.Tazel.Benchmarks/Benchmarks.cs new file mode 100644 index 0000000..8e8dff3 --- /dev/null +++ b/benchmarks/Progmasoft.Tazel.Benchmarks/Benchmarks.cs @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System.Collections.Generic; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Running; +using TazelCommandLine = Progmasoft.Tazel.Cli.CommandLine; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Dsl.Custom.Parser; +using Progmasoft.Tazel.Label; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Benchmarks; + +/// <summary>What a build does many times: read labels, match globs, read depfiles and command lines.</summary> +[MemoryDiagnoser] +public class Readers +{ + private const string Depfile = """ + .tazel/out/linux-amd64-debug/_objs/app/src/main.cpp.o: src/main.cpp \ + /usr/include/stdio.h /usr/include/bits/libc-header-start.h \ + /usr/include/features.h include/math/vec\ tor.hpp include/math/details.inl + """; + + private const string Custom = """ + build-no-cache: ("tazel" 'build' `--no-cache`); + fetch: ("cargo" "fetch") ("tazel" "fetch"); + build with: ("tazel" "build" <1> <2>); + """; + + private static readonly string[] BuildLine = + ["build", "//app/...", "--mode=release", "--compiler-options=-O3,-g", "--feature", "lto", "--color:never"]; + + /// <summary>Reads one label.</summary> + [Benchmark] + public Selection Label() => Labels.Selection("@dep//app/cli:greeter-main", PackageId.Root); + + /// <summary>Matches a path against a pattern with <c>**</c>.</summary> + [Benchmark] + public bool Glob() => FileSets.Matches("src/**/test_*.cpp", "src/a/b/c/test_vector.cpp"); + + /// <summary>Reads the inputs of a depfile.</summary> + [Benchmark] + public IReadOnlyList<string> DepfileInputs() => Depfiles.Inputs(Depfile); + + /// <summary>Reads a tazel_custom.txt.</summary> + [Benchmark] + public int CustomCommands() => CustomParser.Parse(Custom).Count; + + /// <summary>Reads a command line.</summary> + [Benchmark] + public object CommandLineOfABuild() => TazelCommandLine.Parse(BuildLine); +} + +/// <summary>Runs the benchmarks: <c>dotnet run -c Release --project benchmarks/Progmasoft.Tazel.Benchmarks</c>.</summary> +public static class Program +{ + /// <summary>Runs what the arguments select.</summary> + public static void Main(string[] arguments) => BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(arguments); +} diff --git a/benchmarks/Progmasoft.Tazel.Benchmarks/Progmasoft.Tazel.Benchmarks.csproj b/benchmarks/Progmasoft.Tazel.Benchmarks/Progmasoft.Tazel.Benchmarks.csproj new file mode 100644 index 0000000..d78714b --- /dev/null +++ b/benchmarks/Progmasoft.Tazel.Benchmarks/Progmasoft.Tazel.Benchmarks.csproj @@ -0,0 +1,15 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <OutputType>Exe</OutputType> + <GenerateDocumentationFile>false</GenerateDocumentationFile> + <Optimize>true</Optimize> + </PropertyGroup> + <ItemGroup> + <ProjectReference Include="../../src/Progmasoft.Tazel/Progmasoft.Tazel.csproj" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="BenchmarkDotNet" /> + </ItemGroup> +</Project> diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..fc4a6f9 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,14 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# Tazel documentation + +| Document | What it covers | +| --- | --- | +| [Project files](project-files.md) | `MODULE.csx`, `BUILD.csx` and toolchains, with every setting | +| [Commands](commands.md) | the commands of `tazel`, their options, and `tazel_options.txt` and `tazel_custom.txt` | +| [Architecture](architecture.md) | the projects of the solution and how a build runs | +| [Development](development.md) | building, testing, fuzzing and benchmarking Tazel, and its CI | +| [Reference](reference/index.md) | the C# types of the project files, made with DocFX | + +The [README](../README.md) says what Tazel is. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..cc6e9db --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,51 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# Architecture + +## Projects + +| Project | What it is | +| --- | --- | +| `src/Progmasoft.Tazel.Dsl` | the types project files are written against; scripts reference this assembly alone | +| `src/Progmasoft.Tazel` | the `tazel` command | +| `tests/Progmasoft.Tazel.Tests` | xUnit tests, with CsCheck for properties and Snapshooter for snapshots | +| `benchmarks/Progmasoft.Tazel.Benchmarks` | BenchmarkDotNet measurements of the readers | +| `fuzz/Progmasoft.Tazel.Fuzz` | SharpFuzz targets for libFuzzer | + +## Namespaces of tazel + +| Namespace | What it does | +| --- | --- | +| `Progmasoft.Tazel.Cli` | reads the command line into typed commands, selects targets, carries commands out | +| `Progmasoft.Tazel.Label` | reads labels and package patterns | +| `Progmasoft.Tazel.Project` | finds the module and its packages, runs the project files, checks targets and what they depend on | +| `Progmasoft.Tazel.Driver` | chooses toolchains, plans actions, runs them with the action cache, runs tests | +| `Progmasoft.Tazel.Archive` | writes and unpacks `.tazel.tar.xz` archives and reads `.sha256sums` | +| `Progmasoft.Tazel.Output` | prints through Spectre.Console | +| `Progmasoft.Tazel.Dsl.Custom`, `.Lexer`, `.Parser` | `tazel_custom.txt` | +| `Progmasoft.Tazel.Dsl.Options` | `tazel_options.txt`, with the lexer of `tazel_custom.txt` | + +## A build + +1. `CommandLine` reads the arguments into a `BuildCommand`, `TestCommand` or `RunCommand`; nothing later looks at the + text again. +2. `Workspace` finds the nearest `MODULE.csx`, runs it, unpacks and loads the archives it depends on, and runs every + `BUILD.csx` of each module at once. A project file declares its targets and toolchains through the static methods of + the preludes, which record them for the file that is running. +3. `Workspace` checks each target: its settings, what it depends on, visibility, and that no targets depend on each + other. +4. `Selector` turns the labels into targets, leaving out of patterns what is `manual` or does not build for the + platform. +5. `ToolchainChooser` picks the toolchain of each family; `Planner` turns each target into actions: one compilation + per file, then the archive or the link, or one zig command. +6. `Executor` runs the actions as soon as what they read is made, at most `--jobs` at once, skipping each one the + `ActionCache` finds current. +7. `TestRunner` runs the tests that were built, in their runfiles directories, and the reporter prints the summary. + +## The archive of a module + +`$group.$module-$version.tazel.tar.xz` holds the files of the module below one directory of that name: sorted, owned +by no one, dated at the epoch, `0644` or `0755`, compressed by Lzma.Net with one thread. Two archives of the same files +are the same bytes. Unpacking refuses links, devices, absolute paths, `..`, more than one top directory, more than +100,000 entries and more than 1 GiB. diff --git a/docs/commands.md b/docs/commands.md new file mode 100644 index 0000000..ba1c6c5 --- /dev/null +++ b/docs/commands.md @@ -0,0 +1,95 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# Commands + +| Command | What it does | +| --- | --- | +| `tazel build [labels]` | builds the targets of the labels; without a label, those of the package of the current directory | +| `tazel test [labels]` | builds the tests of the labels and runs them | +| `tazel run <label> [-- arguments]` | builds one executable or test and runs it | +| `tazel clean [--expunge]` | removes the outputs, the test logs and zig's cache; `--expunge` removes all of `.tazel` | +| `tazel package` | writes `.tazel/package/$group.$module-$version.tazel.tar.xz` and its `.sha256sums` | +| `tazel custom <name> [arguments]` | runs a command of the `tazel_custom.txt` of the current directory | +| `tazel version`, `tazel help [command]` | print the version, or what Tazel or one command does | + +## Options + +Long options take their value after whitespace, `=` or `:`: `--platform linux-aarch64`, `--platform=linux-aarch64`, +`--platform:linux-aarch64`. A list goes after `=` or `:`, separated by commas without spaces, and `\,` is a comma of a +value; a value after whitespace is one value. A list and a repeated option keep their order: +`--compiler-options=-O2,-g` is `--compiler-options -O2 --compiler-options -g`. Options may stand anywhere before `--`. +A misspelt command, option or value gets a hint that keeps how it was written: `--color:awlyas` suggests +`--color:always`. + +| Option | Commands | | +| --- | --- | --- | +| `--color always\|auto\|never` | all | colors | +| `--progress always\|auto\|never` | all | the `[done/total]` counter of a build | +| `--quiet` | all | only problems and the output of what was run | +| `--help`, `-h` | all | the help of the command | +| `--mode debug\|release` | build, run, test | `debug` is the default | +| `--platform <name>` | build, run, test | the platform to build for | +| `--jobs <n>` | build, run, test | how many actions run at once | +| `--keep-going` | build, run, test | go on with what does not depend on a failed action | +| `--feature <name>`, `--no-feature <name>` | build, run, test | turn a toolchain feature on or off for every target | +| `--compiler-options <option>` | build, run, test | every C, C++, Objective-C and Objective-C++ file | +| `--c-compiler-options <option>` | build, run, test | .c and .m files | +| `--cpp-compiler-options <option>` | build, run, test | .cpp, .cc, .cxx and .mm files | +| `--linker-options <option>` | build, run, test | every link | +| `--zig-compiler-options <option>` | build, run, test | every zig command | + +The options for the compilers and the linker come after the target's own settings, so the command line wins where +the compiler takes the last flag, and they are part of the key of each action. + +The platform comes from `--platform`, else from `tazel_options.txt`, else it is this machine's. `--jobs` and +`--keep-going` win over `Execution` of `MODULE.csx`. + +## Builds, tests and runs + +Each action is a command started directly, without a shell, in the root of the module, with a small environment: +`PATH`, the temporary directory, `HOME`, the SDK variables of macOS and Windows, and `LC_ALL=C`. Outputs go to +`.tazel/out/<platform>-<mode>/`. An action keeps a record beside its first output; it runs again only when its +command line, its environment, an input or an output changed by content. The headers a compilation read come from +its depfile. + +A test runs in its runfiles directory, `<program>.runfiles`, where its `RuntimeData` is at its path in the module. Its +environment is `PATH`, its `InheritedEnvironmentVariables`, `TEST_TMPDIR`, `TEST_SRCDIR`, `TEST_TARGET`, the shard +variables and its `EnvironmentVariables`. Its log is `.tazel/testlogs/<package>/<name>/test.log`. A test tagged +`exclusive` runs alone. + +`tazel run` runs the program in its runfiles directory with Tazel's environment and the program's +`EnvironmentVariables`, its `Arguments` and what follows `--`, and returns its exit status. + +## tazel_options.txt + +```text +# comment +<# comment #> +sandboxing-with-microvm: false; +microvm-network: false; +microvm-memory: 2048; # MiB, or "auto" +microvm-cpus: "auto"; +platform: linux-amd64; +``` + +The nearest `tazel_options.txt` at or above the current directory holds, except that a sandbox asked for by any file +above stays asked for. This Tazel has no MicroVM to start, so with `sandboxing-with-microvm: true` it refuses every +command that would run what a project brings (`build`, `run`, `test`, `package`, `custom`) rather than run it on this +machine. + +## tazel_custom.txt + +```text +build-no-cache: ("tazel" 'build' `--no-cache`); +fetch: + ("cargo" "fetch") + ("tazel" "fetch"); +npm-dev-sh: s('npm dev'); +build with: ("tazel" "build" <1> <2>); +``` + +A command is a name of one or more words, a colon, and steps that run in order until one fails. `("program" "arg")` +starts a program directly; `s("line")` gives one line to the shell (CMD on Windows, `sh` elsewhere). Strings take +double quotes, single quotes or backticks and have no escapes. `<N>` is the Nth argument after the name, `<*>` all of +them. The longest name that fits the command line wins, and `--` ends the name. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..3115880 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,59 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# Development + +Tazel needs the .NET 10 SDK; `global.json` holds it to a 10.0 SDK and runs tests on Microsoft.Testing.Platform. + +```text +dotnet build Tazel.slnx +dotnet test --solution Tazel.slnx +dotnet test --solution Tazel.slnx --coverlet --coverlet-output-format cobertura +dotnet run --project src/Progmasoft.Tazel -- build //... (in a module) +``` + +Every warning of the compiler and of the .NET analyzers is an error. Packages and their versions are in +`Directory.Packages.props`; the tools (SharpFuzz, DocFX) are in `dotnet-tools.json`, restored by `dotnet tool restore`. + +## Tests + +The tests that build with a compiler or zig run when one is on PATH and are skipped otherwise. + +Snapshots are kept with [Snapshooter](https://github.com/SwissLife-OSS/Snapshooter) in +`tests/Progmasoft.Tazel.Tests/__snapshots__/`, through `Snapshots.Match`. A snapshot that differs fails with the lines +that differ, a few lines around each, and the path of the new snapshot in `__snapshots__/__mismatch__/`; when the +change is right, move it over the stored one and commit it. A test without a stored snapshot writes one, except with +`SNAPSHOOTER_STRICT_MODE=true`, as in CI, where it fails. + +## Fuzzing + +The readers of what users write (`tazel_custom.txt`, `tazel_options.txt`, labels, depfiles, command lines) are fuzz +targets. With [libfuzzer-dotnet](https://github.com/Metalnem/libfuzzer-dotnet): + +```text +dotnet tool restore +dotnet publish fuzz/Progmasoft.Tazel.Fuzz -c Release -o artifacts/fuzz +dotnet sharpfuzz artifacts/fuzz/tazel.dll +libfuzzer-dotnet --target_path=artifacts/fuzz/Progmasoft.Tazel.Fuzz --target_arg=custom fuzz/corpus/custom +``` + +A target may refuse an input with the exception of its kind; any other exception, a hang or a crash is a finding. +`fuzz/corpus/` holds the seeds. + +## Benchmarks + +```text +dotnet run -c Release --project benchmarks/Progmasoft.Tazel.Benchmarks -- --filter '*' +``` + +## CI + +| Workflow | What it runs | +| --- | --- | +| `ci.yml` | build and tests on Ubuntu 26.04 (with Zig), Windows Server 2025 and macOS 15, coverage to Codecov, DocFX | +| `fuzzing.yml` | each fuzz target for one minute on a pull request and thirty minutes every night | +| `codeql.yml` | CodeQL for C# and the workflows | +| `dependency-review.yml` | the dependencies a pull request adds | +| `zizmor.yml` | the security of the workflows | + +Renovate proposes updates of the NuGet packages, the tools and the actions once a week, a week after their release. diff --git a/docs/project-files.md b/docs/project-files.md new file mode 100644 index 0000000..e0fd050 --- /dev/null +++ b/docs/project-files.md @@ -0,0 +1,251 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# Project files + +A module is a directory with a `MODULE.csx`. Each directory below it with a `BUILD.csx` is a package; a directory with +a `MODULE.csx` of its own is another module and is not part of this one. Both files are C# scripts, run by Tazel with +the C# scripting of Roslyn; nothing else needs to be installed. Every project file sees `Progmasoft.Tazel.Dsl.Common` +(platforms, `Glob`, `Visibility`, `TestSize`, sizes) without a `using`. + +A package's project file is the first of `BUILD.csx`, `BUILD.tzl`, `BUILD.tazel`, `BUILD` and `Tazel.build` that it +has, looked up case-sensitively; all of them are C# scripts. + +## MODULE.csx + +```cs +using System; +using Progmasoft.Tazel.Dsl.Module.Prelude; + +module = Module.Define(new() { + Group = "com.example", + Name = "greeter", + Version = "1.2.0", // SemVer + Description = "Greets people.", + Authors = ["Leitwolf"], + License = "MIT", // an SPDX expression + Readme = "README.md", // the default + Compatibility = TazelVersion.AtLeast(0, 1) // the Tazel versions it builds with; PATCH may be left out +}); + +dependencies = Dependencies.Define( + LocalModule.From(new() { + Name = "local-lib", // its labels: @local-lib//:x + Include = "deps/local.tazel.tar.xz", // one archive, no glob + Sha256 = "<sha256>" // or Sha256Sums = "deps/local.tazel.tar.xz.sha256sums" + }) +); + +portalModules = PortalModules.Define(new() { + Push = false, + Exclude = [new Glob("docs/**"), "legacy/code.cpp"] // left out of the archive of tazel package +}); + +cache = Cache.Define(new() { Local = true }); // Local = false runs every action every time + +execution = Execution.Define(new() { Jobs = 8, KeepGoing = false }); + +toolchains = Toolchains.Define("//toolchains:clang"); +``` + +- `TazelVersion` has `Exactly`, `AtLeast`, `GreaterThan`, `AtMost`, `LessThan` and `Between`, which includes both + ends. A Tazel outside the range stops with the range and its own version. +- A dependency is a `LocalModule`: Tazel checks its archive against the SHA-256 and unpacks it once below `.tazel/`. + Its public targets are `@name//dir:x`. `Module.From`, a module of Tazel Portal Modules, is refused by this Tazel, + which fetches nothing. +- This Tazel reads `Cache.Remote`, `Execution.Remote`, `Execution.Memory` and `plugins` and says, as a warning, that + it does not act on them. + +## BUILD.csx + +```cs +using System; +using System.Collections.Generic; +using Progmasoft.Tazel.Dsl.Build.Prelude; + +var math = CC.StaticLibrary("math", new() +{ + Sources = new Glob("src/math/*.cpp", exclude: ["src/math/experimental_*.cpp"]), + Headers = new Glob("include/math/*.hpp"), + TextualHeaders = ["include/math/details.inl"], + IncludeDirectories = ["include"], + CompilerOptions = ["-Wall"], // every file + CCompilerOptions = ["-std=c17"], // .c and .m files + CppCompilerOptions = ["-std=c++23"], // .cpp, .cc, .cxx and .mm files + PreprocessorDefinitions = ["MATH_API=1"], // this target and its dependents + LocalPreprocessorDefinitions = ["MATH_BUILD=1"], + LinkerOptions = ["-lm"], // a library's go to whatever links it + AlwaysLink = false, + Features = [CC.Enable("warnings")], + Visibility = Visibility.Public +}); + +CC.SharedLibrary("greeter_shared", new() +{ + Sources = ["src/greeting.cpp", "src/legacy.c"], + Depends = ["//:math"], + LibraryVersion = new Version(1, 2, 0), // libgreeter_shared.so.1.2.0, with the soname libgreeter_shared.so.1 + TargetConstraints = [Platform.LinuxAmd64] +}); + +CC.Executable("greeter", new() +{ + Sources = ["src/main.cpp"], + Depends = [math, ":greeter_shared"], + LinkerOptions = Build.Mode == BuildMode.Release ? ["-s"] : [], + LinkingMode = LinkingMode.PreferStatic, // PreferShared, FullyStatic + RuntimeData = ["assets/messages.txt"], + Arguments = ["--language", "en"], + EnvironmentVariables = new() { ["GREETER_MODE"] = "cli" }, + StampBuildInformation = true // TAZEL_BUILD_LABEL and TAZEL_BUILD_VERSION +}); + +CC.Test("math_test", new() +{ + Sources = ["tests/math_test.cpp"], + Depends = [math, "@catch3//:main"], + TestSize = TestSize.Small, // Small, Medium, Large, Enormous: 1, 5, 15, 60 minutes + Timeout = TimeSpan.FromMinutes(2), + Flaky = false, // true: a failure runs again, up to three times + ShardCount = 2, // TEST_TOTAL_SHARDS and TEST_SHARD_INDEX + InheritedEnvironmentVariables = ["HOME"] +}); +``` + +- **Files.** A string is one path below the project file; `new Glob(pattern, exclude: [...])` is a pattern, with `*`, + `?` and `**`. A glob leaves out hidden files and subpackages. Lists may mix both. +- **Labels.** `//:x` is target `x` of the root `BUILD.csx`, `//dir:x` of `dir/BUILD.csx`, `:x` of the same file, + `@name//dir:x` of a dependency. `Depends` also takes the value a declaration returned. +- **Visibility.** `Private` (the default) is this file only, `Module` every package of the module, `Public` also the + modules that depend on it. +- **Platforms.** `TargetConstraints` names the platforms a target builds for; without it, every platform, except that + `ObjectiveC` targets build for the two macOS platforms. `//...` leaves out a target that does not build for the + platform of the command, with every target that depends on it, and says how many it left out; naming it is an error. + `Tags = ["manual"]` keeps a target out of `//...` as well. +- **Conditions** are C#: `Build.Mode` (`BuildMode.Debug`, `Release`), `Build.Platform`, `Build.Os`, `Build.Arch`. +- **Headers** of a target are found below the root of its module and below its `IncludeDirectories`, by it and by + what depends on it. + +### Objective-C + +```cs +ObjectiveC.StaticLibrary("objc_core", new() +{ + Sources = ["objc/Greeter.m", "objc/GreeterExtension.mm"], + Headers = ["objc/Greeter.h"], + NonAutomaticReferenceCountingSources = ["objc/LegacyMemory.m"], // every other file has ARC + EnableClangModules = true, + ModuleName = "GreeterCore", + ModuleMap = "objc/module.modulemap", + SdkFrameworks = ["Foundation"], + WeakSdkFrameworks = ["Metal"], + SdkDynamicLibraries = ["z"], + Visibility = Visibility.Public +}); + +ObjectiveC.Executable("objc_greeter", new() +{ + Sources = ["objc/main.m"], + Depends = ["//:objc_core"], + Bundle = new() { Identifier = "com.example.greeter", InfoPlist = "objc/Info.plist" } +}); + +ObjectiveC.Test("objc_core_test", new() +{ + Sources = ["objc/tests/GreeterTests.m"], + Depends = ["//:objc_core"], + SdkFrameworks = ["Foundation", "XCTest"], + TestRunner = ObjectiveCTestRunner.XCTest +}); +``` + +`CC` targets take `SdkFrameworks`, `WeakSdkFrameworks` and `SdkDynamicLibraries` too. This Tazel builds an executable +with a `Bundle` as a plain program, and runs every test as an executable judged by its exit status. + +### Zig + +```cs +Zig.Module("zig_core", new() { RootSourceFile = "zig/core.zig", Visibility = Visibility.Public }); + +Zig.StaticLibrary("zig_math", new() +{ + RootSourceFile = "zig/math.zig", + ModuleImports = new Dictionary<string, string> { ["core"] = "//:zig_core" }, + OptimizationMode = ZigOptimization.ReleaseSafe, // Debug, ReleaseSafe, ReleaseFast, ReleaseSmall + PositionIndependentCode = true, + LinkCStandardLibrary = true +}); + +Zig.Executable("zig_greeter", new() +{ + RootSourceFile = "zig/main.zig", + ModuleImports = new Dictionary<string, string> { ["core"] = "//:zig_core" }, + Depends = ["//:zig_math", math], // Zig libraries and C-family libraries + CSources = ["zig/shim.c"], // compiled by zig, with the C options of the target + ZigCompilerOptions = ["-fno-omit-frame-pointer"] +}); + +Zig.Test("zig_core_test", new() { RootSourceFile = "zig/core.zig", TestFilter = "parsing" }); +``` + +- `Sources` names the files the root imports, for the cache; without it, every `.zig` file beside the root file and + below it. +- `OptimizationMode` defaults to `Debug` in a debug build and `ReleaseSafe` in a release build. +- `EmitHeader` passes `-femit-h`; the zig compilers since 0.11 accept it and write no header, so a build that needs the + header stops with that reason. + +## Toolchains + +Toolchains are declared in a `BUILD.csx`, usually `toolchains/BUILD.csx`, and registered by label in `MODULE.csx`. +For each family Tazel takes the first registered toolchain that runs on this machine and builds for the platform of +the command. Without one, it uses this machine's own tools (clang, then gcc, then `zig cc`; zig), and only when the +platform is this machine's. + +```cs +using Progmasoft.Tazel.Dsl.Build.Toolchain.Prelude; + +var warnings = CC.Feature("warnings", new() +{ + Enabled = true, + FlagSets = [ new() { Actions = [CCAction.CCompile, CCAction.CppCompile], Flags = ["-Wall", "-Wextra"] } ] +}); + +var crossToArm = CC.Feature("linux-aarch64", new() +{ + Enabled = true, + FlagSets = + [ + new() + { + Actions = [CCAction.CCompile, CCAction.CppCompile, CCAction.CppLinkExecutable, CCAction.CppLinkSharedLibrary], + Flags = ["--target=aarch64-linux-gnu", "--sysroot=/opt/sysroots/aarch64"] + } + ] +}); + +CC.Toolchain("clang-linux-aarch64", new() +{ + ExecutionPlatform = Platform.LinuxAmd64, + TargetPlatform = Platform.LinuxAarch64, + Tools = new() { CCompiler = "clang", CppCompiler = "clang++", Linker = "clang++", Archiver = "llvm-ar" }, + Features = [warnings, crossToArm] +}); + +Zig.Toolchain("zig", new() +{ + ExecutionPlatform = Platform.LinuxAmd64, + TargetPlatform = Platform.LinuxAmd64, + Tools = new() { Zig = "/opt/zig/zig" } +}); +``` + +- The actions are `CCompile`, `CppCompile`, `ObjectiveCCompile`, `ObjectiveCppCompile`, `Assemble`, + `CppLinkExecutable`, `CppLinkSharedLibrary` and `CppLinkStaticLibrary` (the archiver). +- A command line of a compilation is: the compiler, `-g` in a debug build or `-O2 -DNDEBUG` in a release build, the + flags of the features that are on, `-fPIC` for libraries, the include directories and macros, `CompilerOptions`, + `CCompilerOptions` or `CppCompilerOptions`, and then the options of the command line. +- A feature is on when it is `Enabled`, or `--feature` names it, and off when `--no-feature` names it; a target's + `Features` win over both. +- The platforms are `LinuxAmd64` (`linux-amd64`), `LinuxAarch64`, `WindowsX64`, `WindowsArm64`, `MacOSX86_64` + (`macos-x86_64`), `MacOSArm64`, `FreeBSDAmd64`, `FreeBSDAarch64`, `OpenBSDAmd64`, `OpenBSDAarch64` and + `DragonFlyBSDAmd64`. diff --git a/docs/reference/.gitignore b/docs/reference/.gitignore new file mode 100644 index 0000000..8c6492c --- /dev/null +++ b/docs/reference/.gitignore @@ -0,0 +1 @@ +api/ diff --git a/docs/reference/docfx.json b/docs/reference/docfx.json new file mode 100644 index 0000000..beb01ba --- /dev/null +++ b/docs/reference/docfx.json @@ -0,0 +1,15 @@ +{ + "metadata": [ + { + "src": [{ "src": "../..", "files": ["src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj"] }], + "dest": "api", + "properties": { "TargetFramework": "net10.0" } + } + ], + "build": { + "content": [{ "files": ["api/*.yml", "index.md", "toc.yml"] }], + "dest": "../../artifacts/reference", + "globalMetadata": { "_appTitle": "Tazel project files", "_enableSearch": true }, + "warningsAsErrors": true + } +} diff --git a/docs/reference/index.md b/docs/reference/index.md new file mode 100644 index 0000000..9b7271c --- /dev/null +++ b/docs/reference/index.md @@ -0,0 +1,8 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# Tazel project files + +The reference of the types `MODULE.csx` and `BUILD.csx` are written against: `Progmasoft.Tazel.Dsl.Module.Prelude`, +`Progmasoft.Tazel.Dsl.Build.Prelude`, `Progmasoft.Tazel.Dsl.Build.Toolchain.Prelude`, and +`Progmasoft.Tazel.Dsl.Common`, which every project file sees without a `using`. diff --git a/docs/reference/toc.yml b/docs/reference/toc.yml new file mode 100644 index 0000000..0ec7c47 --- /dev/null +++ b/docs/reference/toc.yml @@ -0,0 +1,4 @@ +- name: Overview + href: index.md +- name: API + href: api/ diff --git a/dotnet-tools.json b/dotnet-tools.json new file mode 100644 index 0000000..152e946 --- /dev/null +++ b/dotnet-tools.json @@ -0,0 +1,20 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "sharpfuzz.commandline": { + "version": "2.3.0", + "commands": [ + "sharpfuzz" + ], + "rollForward": false + }, + "docfx": { + "version": "2.81.0", + "commands": [ + "docfx" + ], + "rollForward": false + } + } +} \ No newline at end of file diff --git a/fuzz/Progmasoft.Tazel.Fuzz/Progmasoft.Tazel.Fuzz.csproj b/fuzz/Progmasoft.Tazel.Fuzz/Progmasoft.Tazel.Fuzz.csproj new file mode 100644 index 0000000..8bfe3cf --- /dev/null +++ b/fuzz/Progmasoft.Tazel.Fuzz/Progmasoft.Tazel.Fuzz.csproj @@ -0,0 +1,14 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <OutputType>Exe</OutputType> + <GenerateDocumentationFile>false</GenerateDocumentationFile> + </PropertyGroup> + <ItemGroup> + <ProjectReference Include="../../src/Progmasoft.Tazel/Progmasoft.Tazel.csproj" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="SharpFuzz" /> + </ItemGroup> +</Project> diff --git a/fuzz/Progmasoft.Tazel.Fuzz/Program.cs b/fuzz/Progmasoft.Tazel.Fuzz/Program.cs new file mode 100644 index 0000000..70cd6f4 --- /dev/null +++ b/fuzz/Progmasoft.Tazel.Fuzz/Program.cs @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Text; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Dsl.Custom; +using Progmasoft.Tazel.Dsl.Custom.Parser; +using Progmasoft.Tazel.Dsl.Options; +using Progmasoft.Tazel.Label; +using Progmasoft.Tazel.Project; +using SharpFuzz; + +namespace Progmasoft.Tazel.Fuzz; + +/// <summary> +/// The readers of what a user writes, under libFuzzer: <c>Progmasoft.Tazel.Fuzz <target></c> with the libFuzzer +/// options after it, from libfuzzer-dotnet. Each target may refuse its input with the exception of its kind, and must +/// do nothing else: no other exception, no hang, no crash. +/// </summary> +public static class Program +{ + /// <summary>The fuzz targets by name.</summary> + public static readonly string[] Targets = ["custom", "options", "label", "depfile", "command-line"]; + + /// <summary>Runs one target on the inputs libFuzzer gives.</summary> + public static void Main(string[] arguments) + { + ArgumentNullException.ThrowIfNull(arguments); + Action<string> target = (arguments.Length > 0 ? arguments[0] : "") switch + { + "custom" => text => Refused<CustomCommandsException>(() => CustomParser.Parse(text)), + "options" => text => Refused<TazelOptionsException>(() => TazelOptionsFile.Parse(text)), + "label" => text => Refused<LabelException>(() => Labels.Selection(text, PackageId.Root)), + "depfile" => text => Depfiles.Inputs(text), + "command-line" => text => Refused<CommandLineException>(() => CommandLine.Parse(text.Split('\n'))), + _ => throw new ArgumentException($"the targets are {string.Join(", ", Targets)}"), + }; + Fuzzer.LibFuzzer.Run(span => + { + string text; + try + { + text = new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(span); + } + catch (DecoderFallbackException) + { + return; + } + + target(text); + }); + } + + private static void Refused<TException>(Action read) + where TException : Exception + { + try + { + read(); + } + catch (TException) + { + // A refusal with a message is what a reader does with what it cannot take. + } + } +} diff --git a/fuzz/corpus/command-line/build b/fuzz/corpus/command-line/build new file mode 100644 index 0000000..c719942 --- /dev/null +++ b/fuzz/corpus/command-line/build @@ -0,0 +1,4 @@ +build +//... +--compiler-options=-O2,-Wl\,x +--color:never \ No newline at end of file diff --git a/fuzz/corpus/custom/notes.txt b/fuzz/corpus/custom/notes.txt new file mode 100644 index 0000000..c3c3287 --- /dev/null +++ b/fuzz/corpus/custom/notes.txt @@ -0,0 +1,65 @@ +# comment +<# comment #> + +build-no-cache: ("tazel" 'build' `--no-cache`); +# The reason for accepting the above is that it accepts double quotes, single quotes, and backticks. + +# No tazel requirement: +npm-dev: ('npm' 'dev'); + +<# +tazel custom build-no-cache +tazel custom npm-dev +#> + +# Multiple: +fetch: + ("cargo" "fetch") + ("tazel" "fetch"); +# Newline insensitive. + +# There are no escape characters. You cannot write " inside "...", ' inside '...', or ` inside `...`. + +# Does not send to the default shell. + +npm-dev-sh: s('npm dev'); + +fetch-sh: + s("cargo fetch") + ("tazel" "fetch"); + +fetch-fully-sh: + s("cargo fetch") + s("tazel fetch"); + +# Those with s(...) go to CMD on Windows, and sh on Linux/macOS. +# s(...) takes exactly one string, the whole command line (USER, 2026-10-31). + +npm-dev-zsh: ("zsh" "-lc" "npm dev"); + +fetch-zsh: + ("zsh" "-lc" "cargo fetch") + ("tazel" "fetch"); + +fetch-fully-zsh: + ("zsh" "-lc" "cargo fetch") + ("zsh" "-lc" "tazel fetch"); + +<# Implemented 2026-11-01. A step's program is a string, and the longest name that fits wins. #> + +# A name may hold several words: +build no-cache: ("tazel" "build" "--no-cache"); +# tazel custom build no-cache +# Everything after `tazel custom`, the words of the name included, is at most 191 arguments: +# this name uses 2, so 189 remain. + +# Arguments of the command line, by position: +build with: ("tazel" "build" <1> <2>); +# tazel custom build with -e MyApp +# <N> starts at 1 and passes the Nth argument; <*> passes all of them. +# s(...) takes no arguments. +<# USER, 2026-11-02. +`tazel custom first second` selects the command `first second` when one exists. For `second` to be an argument of `first`, +either no such command exists, or it is written `tazel custom first -- second`. +Tazel Custom Commands has no escape characters of its own. A line given to the shell is interpreted by that shell, so +Tazel does not process escape characters in it. #> diff --git a/fuzz/corpus/depfile/one b/fuzz/corpus/depfile/one new file mode 100644 index 0000000..faecb94 --- /dev/null +++ b/fuzz/corpus/depfile/one @@ -0,0 +1,2 @@ +a.o: a.c \ + b\ c.h $$x.h diff --git a/fuzz/corpus/label/pattern b/fuzz/corpus/label/pattern new file mode 100644 index 0000000..377d2fc --- /dev/null +++ b/fuzz/corpus/label/pattern @@ -0,0 +1 @@ +@dep//... \ No newline at end of file diff --git a/fuzz/corpus/label/target b/fuzz/corpus/label/target new file mode 100644 index 0000000..fc6d41c --- /dev/null +++ b/fuzz/corpus/label/target @@ -0,0 +1 @@ +//app/cli:main \ No newline at end of file diff --git a/fuzz/corpus/options/notes.txt b/fuzz/corpus/options/notes.txt new file mode 100644 index 0000000..97884d7 --- /dev/null +++ b/fuzz/corpus/options/notes.txt @@ -0,0 +1,13 @@ +# comment +<# comment #> + +sandboxing-with-microvm: true; # When false, Tazel runs with full privileges, and Tazel Custom Commands do not run in a MicroVM; they run on the host system. When true, a MicroVM is used with hardware virtualization (VT-x, AMD-V, etc.). Every potentially dangerous operation (Tazel Plugins, Tazel Custom Commands, etc.) is executed inside a Tazel MicroVM. +microvm-network: true; # Default: false +microvm-memory: 2048; # In MiB. Default: "auto". Users can explicitly specify automatic allocation using "auto", 'auto', or `auto`. +microvm-cpus: 1; # Default: "auto". Users can explicitly specify automatic allocation using "auto", 'auto', or `auto`. + +# Applies not only to commands like `tazel build`, but also to Tazel Custom Commands. + +# A .NET <-> Objective-C bridge is established for the Tazel MicroVM. +# The main Tazel process must remain alive even if the Sandbox Worker crashes. +platform: linux-amd64; # USER, 2026-11-19. Default: the host's. `--platform <name>` on the command line wins. One of linux-amd64, linux-aarch64, windows-x64, windows-arm64, macos-x86_64, macos-arm64, freebsd-amd64, freebsd-aarch64, openbsd-amd64, openbsd-aarch64, dragonfly-bsd-amd64. It selects the toolchain and does not change what BUILD.csx declares; it chooses the toolchain whose TargetPlatform it is. diff --git a/global.json b/global.json new file mode 100644 index 0000000..df32a2e --- /dev/null +++ b/global.json @@ -0,0 +1,10 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature", + "allowPrerelease": false + }, + "test": { + "runner": "Microsoft.Testing.Platform" + } +} diff --git a/src/Progmasoft.Tazel.Dsl/Build/Prelude/CCSettings.cs b/src/Progmasoft.Tazel.Dsl/Build/Prelude/CCSettings.cs new file mode 100644 index 0000000..788e57d --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Build/Prelude/CCSettings.cs @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using Progmasoft.Tazel.Dsl.Common; + +namespace Progmasoft.Tazel.Dsl.Build.Prelude; + +/// <summary>What every target has: what it depends on, who may depend on it, and where it builds.</summary> +public abstract class TargetSettings +{ + /// <summary>The targets this one depends on, by label or by the value their declaration returned.</summary> + public TargetReferences Depends { get; init; } = TargetReferences.None; + + /// <summary>Who may depend on this target; default: <see cref="Visibility.Private"/>.</summary> + public Visibility Visibility { get; init; } = Visibility.Private; + + /// <summary> + /// The platforms this target builds for; default: all. Elsewhere <c>//...</c> skips it, and naming it is an error. + /// </summary> + public IReadOnlyList<Platform> TargetConstraints { get; init; } = []; + + /// <summary>Words for this target; <c>manual</c> keeps it out of <c>//...</c>.</summary> + public IReadOnlyList<string> Tags { get; init; } = []; +} + +/// <summary>A toolchain feature a target turns on or off.</summary> +public sealed class FeatureToggle +{ + internal FeatureToggle(string name, bool enabled) + { + Name = name; + Enabled = enabled; + } + + /// <summary>The name of the feature.</summary> + public string Name { get; } + + /// <summary>Whether it is turned on.</summary> + public bool Enabled { get; } +} + +/// <summary>How an executable links the libraries it depends on.</summary> +public enum LinkingMode +{ + /// <summary>Static libraries where a dependency is one; the default.</summary> + PreferStatic, + + /// <summary>The same, and system libraries as shared libraries.</summary> + PreferShared, + + /// <summary>Everything static, the C library included (<c>-static</c>).</summary> + FullyStatic, +} + +/// <summary>What C, C++, Objective-C and Objective-C++ targets compile and how.</summary> +public abstract class CCSettings : TargetSettings +{ + /// <summary>The files to compile; the language of each comes from its extension.</summary> + public Files Sources { get; init; } = Files.None; + + /// <summary>Headers this target and its dependents include.</summary> + public Files Headers { get; init; } = Files.None; + + /// <summary>Headers that are included but never compiled alone.</summary> + public Files TextualHeaders { get; init; } = Files.None; + + /// <summary>Directories of this target's headers, for it and its dependents.</summary> + public IReadOnlyList<string> IncludeDirectories { get; init; } = []; + + /// <summary>Options for every file.</summary> + public IReadOnlyList<string> CompilerOptions { get; init; } = []; + + /// <summary>Options for .c and .m files.</summary> + public IReadOnlyList<string> CCompilerOptions { get; init; } = []; + + /// <summary>Options for .cpp, .cc, .cxx and .mm files.</summary> + public IReadOnlyList<string> CppCompilerOptions { get; init; } = []; + + /// <summary>Options for the link; a library's go to the links of what depends on it.</summary> + public IReadOnlyList<string> LinkerOptions { get; init; } = []; + + /// <summary>Macros for this target and its dependents.</summary> + public IReadOnlyList<string> PreprocessorDefinitions { get; init; } = []; + + /// <summary>Macros for this target alone.</summary> + public IReadOnlyList<string> LocalPreprocessorDefinitions { get; init; } = []; + + /// <summary>Toolchain features this target turns on or off.</summary> + public IReadOnlyList<FeatureToggle> Features { get; init; } = []; + + /// <summary>Frameworks of the SDK to link (<c>-framework</c>).</summary> + public IReadOnlyList<string> SdkFrameworks { get; init; } = []; + + /// <summary>Frameworks of the SDK to link weakly (<c>-weak_framework</c>).</summary> + public IReadOnlyList<string> WeakSdkFrameworks { get; init; } = []; + + /// <summary>Libraries of the SDK or the system to link (<c>-l</c>).</summary> + public IReadOnlyList<string> SdkDynamicLibraries { get; init; } = []; +} + +/// <summary>A static library.</summary> +public class CCStaticLibrarySettings : CCSettings +{ + /// <summary>Whether every object goes into what links it, used or not.</summary> + public bool AlwaysLink { get; init; } +} + +/// <summary>A shared library.</summary> +public class CCSharedLibrarySettings : CCSettings +{ + /// <summary>The version of the library, as in <c>libx.so.1.2.0</c>; default: none.</summary> + public Version? LibraryVersion { get; init; } + + /// <summary>More files for the linker, such as linker scripts.</summary> + public Files AdditionalLinkerInputs { get; init; } = Files.None; +} + +/// <summary>What a program gets when Tazel runs it.</summary> +public interface IRunSettings +{ + /// <summary>The arguments <c>tazel run</c> and <c>tazel test</c> pass.</summary> + IReadOnlyList<string> Arguments { get; } + + /// <summary>Files the program reads; they sit in its runfiles directory, where it runs.</summary> + Files RuntimeData { get; } + + /// <summary>The environment of the program.</summary> + Dictionary<string, string> EnvironmentVariables { get; } +} + +/// <summary>How a test runs.</summary> +public interface ITestSettings : IRunSettings +{ + /// <summary>Variables of Tazel's environment the test sees too.</summary> + IReadOnlyList<string> InheritedEnvironmentVariables { get; } + + /// <summary>How much the test may take.</summary> + TestSize TestSize { get; } + + /// <summary>The time the test may take; default: from <see cref="TestSize"/>.</summary> + TimeSpan? Timeout { get; } + + /// <summary>Whether a failure is retried, up to three times.</summary> + bool Flaky { get; } + + /// <summary>How many processes share the test (<c>TEST_TOTAL_SHARDS</c>); default: 1.</summary> + int ShardCount { get; } + + /// <summary>Whether the test runs on this machine even when execution is remote.</summary> + bool RunLocally { get; } +} + +/// <summary>An executable.</summary> +public class CCExecutableSettings : CCSettings, IRunSettings +{ + /// <summary>How the executable links its libraries.</summary> + public LinkingMode LinkingMode { get; init; } = LinkingMode.PreferStatic; + + /// <inheritdoc/> + public Files RuntimeData { get; init; } = Files.None; + + /// <inheritdoc/> + public IReadOnlyList<string> Arguments { get; init; } = []; + + /// <inheritdoc/> + public Dictionary<string, string> EnvironmentVariables { get; init; } = new(); + + /// <summary>Whether the label and the module version are compiled in as macros.</summary> + public bool StampBuildInformation { get; init; } + + /// <summary>More files for the linker.</summary> + public Files AdditionalLinkerInputs { get; init; } = Files.None; +} + +/// <summary>A test: an executable Tazel runs and judges by its exit status.</summary> +public class CCTestSettings : CCExecutableSettings, ITestSettings +{ + /// <inheritdoc/> + public IReadOnlyList<string> InheritedEnvironmentVariables { get; init; } = []; + + /// <inheritdoc/> + public TestSize TestSize { get; init; } = TestSize.Medium; + + /// <inheritdoc/> + public TimeSpan? Timeout { get; init; } + + /// <inheritdoc/> + public bool Flaky { get; init; } + + /// <inheritdoc/> + public int ShardCount { get; init; } = 1; + + /// <inheritdoc/> + public bool RunLocally { get; init; } +} diff --git a/src/Progmasoft.Tazel.Dsl/Build/Prelude/Families.cs b/src/Progmasoft.Tazel.Dsl/Build/Prelude/Families.cs new file mode 100644 index 0000000..77c9216 --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Build/Prelude/Families.cs @@ -0,0 +1,134 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System.Runtime.CompilerServices; +using Progmasoft.Tazel.Dsl.Common; + +namespace Progmasoft.Tazel.Dsl.Build.Prelude; + +/// <summary>C and C++ targets; the language of each file comes from its extension.</summary> +public static class CC +{ + /// <summary>Declares a static library.</summary> + public static Target StaticLibrary( + string name, CCStaticLibrarySettings settings, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.CC, TargetKind.StaticLibrary, name, settings, file, line); + + /// <summary>Declares a shared library.</summary> + public static Target SharedLibrary( + string name, CCSharedLibrarySettings settings, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.CC, TargetKind.SharedLibrary, name, settings, file, line); + + /// <summary>Declares an executable.</summary> + public static Target Executable( + string name, CCExecutableSettings settings, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.CC, TargetKind.Executable, name, settings, file, line); + + /// <summary>Declares a test.</summary> + public static Target Test( + string name, CCTestSettings settings, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.CC, TargetKind.Test, name, settings, file, line); + + /// <summary>Turns a toolchain feature on for a target.</summary> + public static FeatureToggle Enable(string name) => new(name, true); + + /// <summary>Turns a toolchain feature off for a target.</summary> + public static FeatureToggle Disable(string name) => new(name, false); +} + +/// <summary>Objective-C and Objective-C++ targets, with C and C++ files beside them.</summary> +public static class ObjectiveC +{ + /// <summary>Declares a static library.</summary> + public static Target StaticLibrary( + string name, ObjectiveCStaticLibrarySettings settings, [CallerFilePath] string file = "", + [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.ObjectiveC, TargetKind.StaticLibrary, name, settings, file, line); + + /// <summary>Declares a shared library.</summary> + public static Target SharedLibrary( + string name, ObjectiveCSharedLibrarySettings settings, [CallerFilePath] string file = "", + [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.ObjectiveC, TargetKind.SharedLibrary, name, settings, file, line); + + /// <summary>Declares an executable.</summary> + public static Target Executable( + string name, ObjectiveCExecutableSettings settings, [CallerFilePath] string file = "", + [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.ObjectiveC, TargetKind.Executable, name, settings, file, line); + + /// <summary>Declares a test.</summary> + public static Target Test( + string name, ObjectiveCTestSettings settings, [CallerFilePath] string file = "", + [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.ObjectiveC, TargetKind.Test, name, settings, file, line); + + /// <summary>Turns a toolchain feature on for a target.</summary> + public static FeatureToggle Enable(string name) => new(name, true); + + /// <summary>Turns a toolchain feature off for a target.</summary> + public static FeatureToggle Disable(string name) => new(name, false); +} + +/// <summary>Zig targets.</summary> +public static class Zig +{ + /// <summary>Declares a module, which other Zig targets import.</summary> + public static Target Module( + string name, ZigModuleSettings settings, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.Zig, TargetKind.Module, name, settings, file, line); + + /// <summary>Declares a static library.</summary> + public static Target StaticLibrary( + string name, ZigStaticLibrarySettings settings, [CallerFilePath] string file = "", + [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.Zig, TargetKind.StaticLibrary, name, settings, file, line); + + /// <summary>Declares a shared library.</summary> + public static Target SharedLibrary( + string name, ZigSharedLibrarySettings settings, [CallerFilePath] string file = "", + [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.Zig, TargetKind.SharedLibrary, name, settings, file, line); + + /// <summary>Declares an executable.</summary> + public static Target Executable( + string name, ZigExecutableSettings settings, [CallerFilePath] string file = "", + [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.Zig, TargetKind.Executable, name, settings, file, line); + + /// <summary>Declares a test, which <c>zig test</c> builds.</summary> + public static Target Test( + string name, ZigTestSettings settings, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) => + Declarations.Declare(Family.Zig, TargetKind.Test, name, settings, file, line); +} + +/// <summary>What a project file can ask about the build it is part of.</summary> +public sealed class BuildContext +{ + internal BuildContext(BuildMode mode, Platform platform) + { + Mode = mode; + Platform = platform; + } + + /// <summary>Whether the build is a debug or a release build.</summary> + public BuildMode Mode { get; } + + /// <summary>The platform the command builds for.</summary> + public Platform Platform { get; } + + /// <summary>The operating system of <see cref="Platform"/>.</summary> + public Os Os => Platform.GetOs(); + + /// <summary>The architecture of <see cref="Platform"/>.</summary> + public Arch Arch => Platform.GetArch(); +} + +/// <summary>What a <c>BUILD.csx</c> sees beyond its imports.</summary> +public sealed class BuildGlobals +{ + internal BuildGlobals(BuildContext build) => Build = build; + + /// <summary>The build this file is part of.</summary> + public BuildContext Build { get; } +} diff --git a/src/Progmasoft.Tazel.Dsl/Build/Prelude/ObjectiveCSettings.cs b/src/Progmasoft.Tazel.Dsl/Build/Prelude/ObjectiveCSettings.cs new file mode 100644 index 0000000..998421a --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Build/Prelude/ObjectiveCSettings.cs @@ -0,0 +1,126 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System.Collections.Generic; +using Progmasoft.Tazel.Dsl.Common; + +namespace Progmasoft.Tazel.Dsl.Build.Prelude; + +/// <summary>What Objective-C targets have beyond C and C++ ones.</summary> +public interface IObjectiveCSettings +{ + /// <summary>Files compiled without automatic reference counting; every other file has it.</summary> + Files NonAutomaticReferenceCountingSources { get; } + + /// <summary>Whether Clang modules are on (<c>-fmodules</c>).</summary> + bool EnableClangModules { get; } + + /// <summary>The name of the module this target is (<c>-fmodule-name</c>).</summary> + string? ModuleName { get; } + + /// <summary>The module map of this target.</summary> + string? ModuleMap { get; } +} + +/// <summary>How an Objective-C test runs.</summary> +public enum ObjectiveCTestRunner +{ + /// <summary>The test is an XCTest bundle that <c>xctest</c> runs.</summary> + XCTest, + + /// <summary>The test is an executable judged by its exit status.</summary> + Executable, +} + +/// <summary>A macOS application bundle (<c>.app</c>).</summary> +public sealed class Bundle +{ + /// <summary>The bundle identifier, such as <c>com.example.greeter</c>.</summary> + public string Identifier { get; init; } = ""; + + /// <summary>The <c>Info.plist</c> of the bundle.</summary> + public string? InfoPlist { get; init; } + + /// <summary>Files for <c>Contents/Resources</c>.</summary> + public Files Resources { get; init; } = Files.None; + + /// <summary>The identity that signs the bundle; default: not signed.</summary> + public string? CodeSigningIdentity { get; init; } +} + +/// <summary>An Objective-C static library.</summary> +public sealed class ObjectiveCStaticLibrarySettings : CCStaticLibrarySettings, IObjectiveCSettings +{ + /// <inheritdoc/> + public Files NonAutomaticReferenceCountingSources { get; init; } = Files.None; + + /// <inheritdoc/> + public bool EnableClangModules { get; init; } + + /// <inheritdoc/> + public string? ModuleName { get; init; } + + /// <inheritdoc/> + public string? ModuleMap { get; init; } +} + +/// <summary>An Objective-C shared library.</summary> +public sealed class ObjectiveCSharedLibrarySettings : CCSharedLibrarySettings, IObjectiveCSettings +{ + /// <inheritdoc/> + public Files NonAutomaticReferenceCountingSources { get; init; } = Files.None; + + /// <inheritdoc/> + public bool EnableClangModules { get; init; } + + /// <inheritdoc/> + public string? ModuleName { get; init; } + + /// <inheritdoc/> + public string? ModuleMap { get; init; } +} + +/// <summary>An Objective-C executable, a plain program or an application bundle.</summary> +public sealed class ObjectiveCExecutableSettings : CCExecutableSettings, IObjectiveCSettings +{ + /// <inheritdoc/> + public Files NonAutomaticReferenceCountingSources { get; init; } = Files.None; + + /// <inheritdoc/> + public bool EnableClangModules { get; init; } + + /// <inheritdoc/> + public string? ModuleName { get; init; } + + /// <inheritdoc/> + public string? ModuleMap { get; init; } + + /// <summary>The application bundle; default: a plain program.</summary> + public Bundle? Bundle { get; init; } +} + +/// <summary>An Objective-C test.</summary> +public sealed class ObjectiveCTestSettings : CCTestSettings, IObjectiveCSettings +{ + /// <inheritdoc/> + public Files NonAutomaticReferenceCountingSources { get; init; } = Files.None; + + /// <inheritdoc/> + public bool EnableClangModules { get; init; } + + /// <inheritdoc/> + public string? ModuleName { get; init; } + + /// <inheritdoc/> + public string? ModuleMap { get; init; } + + /// <summary>How the test runs; default: <see cref="ObjectiveCTestRunner.Executable"/>.</summary> + public ObjectiveCTestRunner TestRunner { get; init; } = ObjectiveCTestRunner.Executable; +} + +/// <summary>The Objective-C targets have these defaults beyond those of C and C++.</summary> +internal static class ObjectiveCDefaults +{ + /// <summary>Where an Objective-C target builds when it names no platforms: the SDK frameworks are Apple's.</summary> + public static IReadOnlyList<Platform> Platforms { get; } = [Platform.MacOSArm64, Platform.MacOSX86_64]; +} diff --git a/src/Progmasoft.Tazel.Dsl/Build/Prelude/ZigSettings.cs b/src/Progmasoft.Tazel.Dsl/Build/Prelude/ZigSettings.cs new file mode 100644 index 0000000..09beb28 --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Build/Prelude/ZigSettings.cs @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using Progmasoft.Tazel.Dsl.Common; + +namespace Progmasoft.Tazel.Dsl.Build.Prelude; + +/// <summary>How zig optimizes, as its <c>-O</c> names it.</summary> +public enum ZigOptimization +{ + /// <summary>No optimization, every safety check.</summary> + Debug, + + /// <summary>Optimized, with safety checks.</summary> + ReleaseSafe, + + /// <summary>Optimized for speed, without safety checks.</summary> + ReleaseFast, + + /// <summary>Optimized for size, without safety checks.</summary> + ReleaseSmall, +} + +/// <summary>A Zig module: a root file other Zig targets import by a name.</summary> +public class ZigModuleSettings : TargetSettings +{ + /// <summary>The root file of the module.</summary> + public string RootSourceFile { get; init; } = ""; + + /// <summary> + /// The files the root imports, for the cache; default: every <c>.zig</c> file beside the root file and below it. + /// </summary> + public Files Sources { get; init; } = Files.None; + + /// <summary>The modules this one imports: the name <c>@import</c> uses, and the label of a Zig module.</summary> + public Dictionary<string, string> ModuleImports { get; init; } = new(); + + /// <summary>How zig optimizes; default: Debug in a debug build, ReleaseSafe in a release build.</summary> + public ZigOptimization? OptimizationMode { get; init; } +} + +/// <summary>What every Zig target that zig compiles has.</summary> +public abstract class ZigCompiledSettings : ZigModuleSettings +{ + /// <summary>C and C++ files zig compiles into the target.</summary> + public Files CSources { get; init; } = Files.None; + + /// <summary>Options for every file of <see cref="CSources"/>.</summary> + public IReadOnlyList<string> CompilerOptions { get; init; } = []; + + /// <summary>Options for the .c files of <see cref="CSources"/>.</summary> + public IReadOnlyList<string> CCompilerOptions { get; init; } = []; + + /// <summary>Options for the .cpp files of <see cref="CSources"/>.</summary> + public IReadOnlyList<string> CppCompilerOptions { get; init; } = []; + + /// <summary>Options for zig itself, as written.</summary> + public IReadOnlyList<string> ZigCompilerOptions { get; init; } = []; + + /// <summary>Options for the linker.</summary> + public IReadOnlyList<string> LinkerOptions { get; init; } = []; + + /// <summary>Whether the C library is linked (<c>-lc</c>).</summary> + public bool LinkCStandardLibrary { get; init; } + + /// <summary>Whether the code is position independent (<c>-fPIC</c>).</summary> + public bool PositionIndependentCode { get; init; } + + /// <summary>Whether symbols are stripped (<c>-fstrip</c>).</summary> + public bool StripSymbols { get; init; } + + /// <summary>Whether link-time optimization is on (<c>-flto</c>).</summary> + public bool LinkTimeOptimization { get; init; } +} + +/// <summary>A Zig static library.</summary> +public sealed class ZigStaticLibrarySettings : ZigCompiledSettings +{ + /// <summary>The C header zig emits (<c>-femit-h</c>); default: none.</summary> + public string? EmitHeader { get; init; } +} + +/// <summary>A Zig shared library.</summary> +public sealed class ZigSharedLibrarySettings : ZigCompiledSettings +{ + /// <summary>The version of the library; default: none.</summary> + public Version? LibraryVersion { get; init; } + + /// <summary>The C header zig emits (<c>-femit-h</c>); default: none.</summary> + public string? EmitHeader { get; init; } +} + +/// <summary>A Zig executable.</summary> +public class ZigExecutableSettings : ZigCompiledSettings, IRunSettings +{ + /// <inheritdoc/> + public IReadOnlyList<string> Arguments { get; init; } = []; + + /// <inheritdoc/> + public Files RuntimeData { get; init; } = Files.None; + + /// <inheritdoc/> + public Dictionary<string, string> EnvironmentVariables { get; init; } = new(); +} + +/// <summary>A Zig test, which <c>zig test</c> builds.</summary> +public sealed class ZigTestSettings : ZigExecutableSettings, ITestSettings +{ + /// <summary>Runs only the tests whose names hold this text (<c>--test-filter</c>).</summary> + public string? TestFilter { get; init; } + + /// <inheritdoc/> + public IReadOnlyList<string> InheritedEnvironmentVariables { get; init; } = []; + + /// <inheritdoc/> + public TestSize TestSize { get; init; } = TestSize.Medium; + + /// <inheritdoc/> + public TimeSpan? Timeout { get; init; } + + /// <inheritdoc/> + public bool Flaky { get; init; } + + /// <inheritdoc/> + public int ShardCount { get; init; } = 1; + + /// <inheritdoc/> + public bool RunLocally { get; init; } +} diff --git a/src/Progmasoft.Tazel.Dsl/Build/Toolchain/Prelude/Toolchains.cs b/src/Progmasoft.Tazel.Dsl/Build/Toolchain/Prelude/Toolchains.cs new file mode 100644 index 0000000..40d6cba --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Build/Toolchain/Prelude/Toolchains.cs @@ -0,0 +1,164 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Progmasoft.Tazel.Dsl.Common; + +namespace Progmasoft.Tazel.Dsl.Build.Toolchain.Prelude; + +/// <summary>The actions of a C-family build, as Bazel names them, for the flags of a feature.</summary> +public enum CCAction +{ + /// <summary>Compiling a .c file.</summary> + CCompile, + + /// <summary>Compiling a .cpp, .cc or .cxx file.</summary> + CppCompile, + + /// <summary>Compiling a .m file.</summary> + ObjectiveCCompile, + + /// <summary>Compiling a .mm file.</summary> + ObjectiveCppCompile, + + /// <summary>Assembling a .s or .S file.</summary> + Assemble, + + /// <summary>Linking an executable.</summary> + CppLinkExecutable, + + /// <summary>Linking a shared library.</summary> + CppLinkSharedLibrary, + + /// <summary>Making a static library with the archiver.</summary> + CppLinkStaticLibrary, +} + +/// <summary>Flags that go to the tool of some actions.</summary> +public sealed class FlagSet +{ + /// <summary>The actions the flags go to.</summary> + public IReadOnlyList<CCAction> Actions { get; init; } = []; + + /// <summary>The flags, as written.</summary> + public IReadOnlyList<string> Flags { get; init; } = []; +} + +/// <summary>What a feature does and whether it is on by default.</summary> +public sealed class FeatureSettings +{ + /// <summary>Whether the feature is on unless a target or the command line turns it off.</summary> + public bool Enabled { get; init; } + + /// <summary>The flags of the feature.</summary> + public IReadOnlyList<FlagSet> FlagSets { get; init; } = []; +} + +/// <summary>A named set of flags of a toolchain.</summary> +public sealed class Feature +{ + internal Feature(string name, FeatureSettings settings) + { + Name = name; + Settings = settings; + } + + /// <summary>The name targets and <c>--feature</c> use.</summary> + public string Name { get; } + + /// <summary>What the feature does.</summary> + public FeatureSettings Settings { get; } +} + +/// <summary>The programs of a C-family toolchain; a bare name is looked up on PATH.</summary> +public sealed class CCTools +{ + /// <summary>The C compiler, for .c and .m files.</summary> + public string? CCompiler { get; init; } + + /// <summary>The C++ compiler, for .cpp and .mm files.</summary> + public string? CppCompiler { get; init; } + + /// <summary>The program that links; default: the C++ compiler.</summary> + public string? Linker { get; init; } + + /// <summary>The archiver of static libraries.</summary> + public string? Archiver { get; init; } + + /// <summary>clang-tidy, for <c>tazel lint</c>.</summary> + public string? ClangTidy { get; init; } + + /// <summary>clang-format, for <c>tazel format</c>.</summary> + public string? ClangFormat { get; init; } +} + +/// <summary>A C-family toolchain: the platform it runs on, the one it builds for, its tools and features.</summary> +public sealed class CCToolchainSettings +{ + /// <summary>The platform the tools run on.</summary> + public Platform ExecutionPlatform { get; init; } + + /// <summary>The platform the tools build for.</summary> + public Platform TargetPlatform { get; init; } + + /// <summary>The tools.</summary> + public CCTools Tools { get; init; } = new(); + + /// <summary>The features targets may turn on and off.</summary> + public IReadOnlyList<Feature> Features { get; init; } = []; +} + +/// <summary>The programs of a Zig toolchain.</summary> +public sealed class ZigTools +{ + /// <summary>The zig program; a bare name is looked up on PATH.</summary> + public string? Zig { get; init; } +} + +/// <summary>A Zig toolchain.</summary> +public sealed class ZigToolchainSettings +{ + /// <summary>The platform zig runs on.</summary> + public Platform ExecutionPlatform { get; init; } + + /// <summary>The platform zig builds for.</summary> + public Platform TargetPlatform { get; init; } + + /// <summary>The tools.</summary> + public ZigTools Tools { get; init; } = new(); +} + +/// <summary>C and C++ toolchains and their features.</summary> +public static class CC +{ + /// <summary>A feature, for the <c>Features</c> of toolchains.</summary> + public static Feature Feature(string name, FeatureSettings settings) + { + Names.Check(name, "feature name", "a feature"); + return new Feature(name, settings); + } + + /// <summary>Declares a toolchain; MODULE.csx registers it by its label.</summary> + public static void Toolchain( + string name, CCToolchainSettings settings, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) => + Declarations.DeclareToolchain(Family.CC, name, settings, file, line); +} + +/// <summary>Objective-C toolchains.</summary> +public static class ObjectiveC +{ + /// <summary>Declares a toolchain; MODULE.csx registers it by its label.</summary> + public static void Toolchain( + string name, CCToolchainSettings settings, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) => + Declarations.DeclareToolchain(Family.ObjectiveC, name, settings, file, line); +} + +/// <summary>Zig toolchains.</summary> +public static class Zig +{ + /// <summary>Declares a toolchain; MODULE.csx registers it by its label.</summary> + public static void Toolchain( + string name, ZigToolchainSettings settings, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) => + Declarations.DeclareToolchain(Family.Zig, name, settings, file, line); +} diff --git a/src/Progmasoft.Tazel.Dsl/Common/Files.cs b/src/Progmasoft.Tazel.Dsl/Common/Files.cs new file mode 100644 index 0000000..e738eb4 --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Common/Files.cs @@ -0,0 +1,117 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Progmasoft.Tazel.Dsl.Common; + +/// <summary> +/// A pattern of files below the directory of the project file: <c>*</c> stands for any part of one name, +/// <c>?</c> for one character, and <c>**</c> for any number of directories. +/// </summary> +/// <param name="pattern">The pattern, with <c>/</c> between directories.</param> +/// <param name="exclude">Patterns of files to leave out.</param> +public sealed class Glob(string pattern, IReadOnlyList<string>? exclude = null) +{ + /// <summary>The pattern.</summary> + public string Pattern { get; } = pattern; + + /// <summary>Patterns of files the glob leaves out.</summary> + public IReadOnlyList<string> Exclude { get; } = exclude ?? []; + + /// <inheritdoc/> + public override string ToString() => $"new Glob(\"{Pattern}\")"; +} + +/// <summary>One path, or a <see cref="Common.Glob"/>; a list of files may mix both.</summary> +public sealed class FilePattern +{ + private FilePattern(string? path, Glob? glob) + { + Path = path; + Glob = glob; + } + + /// <summary>The path, when this is one path.</summary> + public string? Path { get; } + + /// <summary>The glob, when this is a pattern.</summary> + public Glob? Glob { get; } + + /// <summary>One path.</summary> + public static implicit operator FilePattern(string path) => FromPath(path); + + /// <summary>A pattern.</summary> + public static implicit operator FilePattern(Glob glob) => FromGlob(glob); + + /// <summary>One path.</summary> + public static FilePattern FromPath(string path) + { + ArgumentNullException.ThrowIfNull(path); + return new FilePattern(path, null); + } + + /// <summary>A pattern.</summary> + public static FilePattern FromGlob(Glob glob) + { + ArgumentNullException.ThrowIfNull(glob); + return new FilePattern(null, glob); + } + + /// <inheritdoc/> + public override string ToString() => Path is null ? Glob!.ToString() : $"\"{Path}\""; +} + +/// <summary> +/// Files of a target: <c>["a.c", "b.c"]</c>, <c>new Glob("src/*.c")</c>, or both in one list. +/// </summary> +[CollectionBuilder(typeof(Files), nameof(Create))] +public sealed class Files : IEnumerable<FilePattern> +{ + private readonly FilePattern[] _items; + + private Files(FilePattern[] items) => _items = items; + + /// <summary>No files.</summary> + public static Files None { get; } = new([]); + + /// <summary>The patterns, in their order.</summary> + public IReadOnlyList<FilePattern> Items => _items; + + /// <summary>The files of one glob.</summary> + public static implicit operator Files(Glob glob) => FromGlob(glob); + + /// <summary>The files of one glob.</summary> + public static Files FromGlob(Glob glob) => new([FilePattern.FromGlob(glob)]); + + /// <summary>Builds the files of a collection expression.</summary> + public static Files Create(ReadOnlySpan<FilePattern> items) => new(items.ToArray()); + + /// <inheritdoc/> + public IEnumerator<FilePattern> GetEnumerator() => ((IEnumerable<FilePattern>)_items).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} + +/// <summary>An amount of memory.</summary> +/// <param name="Bytes">The amount in bytes.</param> +public readonly record struct ByteSize(long Bytes); + +/// <summary>Amounts of memory written as <c>16L.Gibibytes()</c>.</summary> +public static class ByteSizes +{ + /// <summary><paramref name="amount"/> bytes.</summary> + public static ByteSize Bytes(this long amount) => new(amount); + + /// <summary><paramref name="amount"/> KiB.</summary> + public static ByteSize Kibibytes(this long amount) => new(checked(amount * 1024)); + + /// <summary><paramref name="amount"/> MiB.</summary> + public static ByteSize Mebibytes(this long amount) => new(checked(amount * 1024 * 1024)); + + /// <summary><paramref name="amount"/> GiB.</summary> + public static ByteSize Gibibytes(this long amount) => new(checked(amount * 1024 * 1024 * 1024)); +} diff --git a/src/Progmasoft.Tazel.Dsl/Common/Platform.cs b/src/Progmasoft.Tazel.Dsl/Common/Platform.cs new file mode 100644 index 0000000..66e7df9 --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Common/Platform.cs @@ -0,0 +1,149 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; + +namespace Progmasoft.Tazel.Dsl.Common; + +/// <summary> +/// A platform Tazel builds for. Each member follows its name on the command line +/// (<c>--platform linux-amd64</c> is <see cref="LinuxAmd64"/>). +/// </summary> +public enum Platform +{ + /// <summary><c>linux-amd64</c>.</summary> + LinuxAmd64, + + /// <summary><c>linux-aarch64</c>.</summary> + LinuxAarch64, + + /// <summary><c>windows-x64</c>.</summary> + WindowsX64, + + /// <summary><c>windows-arm64</c>.</summary> + WindowsArm64, + + /// <summary><c>macos-x86_64</c>.</summary> + MacOSX86_64, + + /// <summary><c>macos-arm64</c>.</summary> + MacOSArm64, + + /// <summary><c>freebsd-amd64</c>.</summary> + FreeBSDAmd64, + + /// <summary><c>freebsd-aarch64</c>.</summary> + FreeBSDAarch64, + + /// <summary><c>openbsd-amd64</c>.</summary> + OpenBSDAmd64, + + /// <summary><c>openbsd-aarch64</c>.</summary> + OpenBSDAarch64, + + /// <summary><c>dragonfly-bsd-amd64</c>; DragonFly BSD runs on x86-64 only.</summary> + DragonFlyBSDAmd64, +} + +/// <summary>An operating system, as conditions in a project file see it.</summary> +public enum Os +{ + /// <summary>Linux.</summary> + Linux, + + /// <summary>Windows.</summary> + Windows, + + /// <summary>macOS.</summary> + MacOS, + + /// <summary>FreeBSD.</summary> + FreeBSD, + + /// <summary>OpenBSD.</summary> + OpenBSD, + + /// <summary>DragonFly BSD.</summary> + DragonFlyBSD, +} + +/// <summary>A processor architecture.</summary> +public enum Arch +{ + /// <summary>x86-64.</summary> + X64, + + /// <summary>64-bit ARM.</summary> + Arm64, +} + +/// <summary>How a build compiles: for debugging, or optimized.</summary> +public enum BuildMode +{ + /// <summary>Not optimized, with debug information.</summary> + Debug, + + /// <summary>Optimized, without assertions.</summary> + Release, +} + +/// <summary>The names, systems and architectures of the platforms.</summary> +public static class Platforms +{ + private static readonly (Platform Platform, string Name, Os Os, Arch Arch)[] All = + [ + (Platform.LinuxAmd64, "linux-amd64", Os.Linux, Arch.X64), + (Platform.LinuxAarch64, "linux-aarch64", Os.Linux, Arch.Arm64), + (Platform.WindowsX64, "windows-x64", Os.Windows, Arch.X64), + (Platform.WindowsArm64, "windows-arm64", Os.Windows, Arch.Arm64), + (Platform.MacOSX86_64, "macos-x86_64", Os.MacOS, Arch.X64), + (Platform.MacOSArm64, "macos-arm64", Os.MacOS, Arch.Arm64), + (Platform.FreeBSDAmd64, "freebsd-amd64", Os.FreeBSD, Arch.X64), + (Platform.FreeBSDAarch64, "freebsd-aarch64", Os.FreeBSD, Arch.Arm64), + (Platform.OpenBSDAmd64, "openbsd-amd64", Os.OpenBSD, Arch.X64), + (Platform.OpenBSDAarch64, "openbsd-aarch64", Os.OpenBSD, Arch.Arm64), + (Platform.DragonFlyBSDAmd64, "dragonfly-bsd-amd64", Os.DragonFlyBSD, Arch.X64), + ]; + + /// <summary>Every platform name, in the order of the enum.</summary> + public static IReadOnlyList<string> Names { get; } = Array.ConvertAll(All, entry => entry.Name); + + /// <summary>The name of <paramref name="platform"/> on the command line.</summary> + public static string Name(this Platform platform) => Find(platform).Name; + + /// <summary>The operating system of <paramref name="platform"/>.</summary> + public static Os GetOs(this Platform platform) => Find(platform).Os; + + /// <summary>The architecture of <paramref name="platform"/>.</summary> + public static Arch GetArch(this Platform platform) => Find(platform).Arch; + + /// <summary>Whether <paramref name="name"/> is a platform name, and which.</summary> + public static bool TryParse(string name, out Platform platform) + { + foreach (var entry in All) + { + if (string.Equals(entry.Name, name, StringComparison.Ordinal)) + { + platform = entry.Platform; + return true; + } + } + + platform = default; + return false; + } + + private static (Platform Platform, string Name, Os Os, Arch Arch) Find(Platform platform) + { + foreach (var entry in All) + { + if (entry.Platform == platform) + { + return entry; + } + } + + throw new ArgumentOutOfRangeException(nameof(platform), platform, "not a platform"); + } +} diff --git a/src/Progmasoft.Tazel.Dsl/Common/References.cs b/src/Progmasoft.Tazel.Dsl/Common/References.cs new file mode 100644 index 0000000..6308e38 --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Common/References.cs @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Progmasoft.Tazel.Dsl.Common; + +/// <summary>Which targets may depend on a target.</summary> +public enum Visibility +{ + /// <summary>Only the targets of the same project file.</summary> + Private, + + /// <summary>Every package of the module.</summary> + Module, + + /// <summary>Every package of the module and the modules that depend on it.</summary> + Public, +} + +/// <summary>How much a test may take; it sets the default timeout.</summary> +public enum TestSize +{ + /// <summary>One minute.</summary> + Small, + + /// <summary>Five minutes.</summary> + Medium, + + /// <summary>Fifteen minutes.</summary> + Large, + + /// <summary>Sixty minutes.</summary> + Enormous, +} + +/// <summary>A target a project file declared; <c>Depends</c> takes it as well as its label.</summary> +public sealed class Target +{ + internal Target(string label) => Label = label; + + /// <summary>The label of the target, such as <c>//core:math</c>.</summary> + public string Label { get; } + + /// <inheritdoc/> + public override string ToString() => Label; +} + +/// <summary>A target that another depends on: its label, or the value its declaration returned.</summary> +public sealed class TargetReference +{ + private TargetReference(string label) => Label = label; + + /// <summary>The label as written, such as <c>//:math</c>, <c>:math</c> or <c>@dep//:x</c>.</summary> + public string Label { get; } + + /// <summary>A label.</summary> + public static implicit operator TargetReference(string label) => FromLabel(label); + + /// <summary>A declared target.</summary> + public static implicit operator TargetReference(Target target) => FromTarget(target); + + /// <summary>A label.</summary> + public static TargetReference FromLabel(string label) + { + ArgumentNullException.ThrowIfNull(label); + return new TargetReference(label); + } + + /// <summary>A declared target.</summary> + public static TargetReference FromTarget(Target target) + { + ArgumentNullException.ThrowIfNull(target); + return new TargetReference(target.Label); + } + + /// <inheritdoc/> + public override string ToString() => Label; +} + +/// <summary>The targets a target depends on: <c>["//:math", math]</c>.</summary> +[CollectionBuilder(typeof(TargetReferences), nameof(Create))] +public sealed class TargetReferences : IEnumerable<TargetReference> +{ + private readonly TargetReference[] _items; + + private TargetReferences(TargetReference[] items) => _items = items; + + /// <summary>No targets.</summary> + public static TargetReferences None { get; } = new([]); + + /// <summary>The references, in their order.</summary> + public IReadOnlyList<TargetReference> Items => _items; + + /// <summary>Builds the references of a collection expression.</summary> + public static TargetReferences Create(ReadOnlySpan<TargetReference> items) => new(items.ToArray()); + + /// <inheritdoc/> + public IEnumerator<TargetReference> GetEnumerator() => + ((IEnumerable<TargetReference>)_items).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/src/Progmasoft.Tazel.Dsl/Declarations.cs b/src/Progmasoft.Tazel.Dsl/Declarations.cs new file mode 100644 index 0000000..ef12e03 --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Declarations.cs @@ -0,0 +1,150 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using System.Threading; +using Progmasoft.Tazel.Dsl.Common; + +namespace Progmasoft.Tazel.Dsl; + +/// <summary>What a project file wrote wrong, with the line it wrote it on.</summary> +public sealed class DslException : Exception +{ + /// <summary>A problem without a place.</summary> + public DslException(string message) + : base(message) + { + } + + /// <summary>A problem and its cause.</summary> + public DslException(string message, Exception inner) + : base(message, inner) + { + } + + /// <summary>Nothing to say.</summary> + public DslException() + { + } +} + +/// <summary>The languages a target is written in.</summary> +internal enum Family +{ + CC, + ObjectiveC, + Zig, +} + +/// <summary>What a target makes.</summary> +internal enum TargetKind +{ + StaticLibrary, + SharedLibrary, + Executable, + Test, + Module, +} + +/// <summary>A target as a project file declared it, before anything is checked against other files.</summary> +internal sealed record TargetDeclaration( + Family Family, TargetKind Kind, string Name, string Label, object Settings, string File, int Line); + +/// <summary>A toolchain as a project file declared it.</summary> +internal sealed record ToolchainDeclaration( + Family Family, string Name, string Label, object Settings, string File, int Line); + +/// <summary>What one project file declares while it runs.</summary> +internal sealed class DeclarationScope(string packagePath, string file) +{ + private readonly HashSet<string> _names = new(StringComparer.Ordinal); + + public string PackagePath { get; } = packagePath; + + public string File { get; } = file; + + public List<TargetDeclaration> Targets { get; } = []; + + public List<ToolchainDeclaration> Toolchains { get; } = []; + + public string LabelOf(string name) => PackagePath.Length == 0 ? $"//:{name}" : $"//{PackagePath}:{name}"; + + public string Claim(string name, int line) + { + Names.Check(name, "target name", Place(line)); + if (!_names.Add(name)) + { + throw new DslException($"{Place(line)}: '{name}' is declared twice in this file"); + } + + return LabelOf(name); + } + + public string Place(int line) => $"{File}:{line}"; +} + +/// <summary>Checks the names a project file gives.</summary> +internal static partial class Names +{ + public static void Check(string name, string what, string place) + { + ArgumentNullException.ThrowIfNull(name); + if (!Pattern().IsMatch(name)) + { + throw new DslException( + $"{place}: the {what} '{name}' must be letters, digits and _ + . -"); + } + } + + [GeneratedRegex("^[A-Za-z0-9_+.-]+$")] + private static partial Regex Pattern(); +} + +/// <summary>The project file that is running, for the declarations it makes.</summary> +internal static class Declarations +{ + private static readonly AsyncLocal<DeclarationScope?> CurrentScope = new(); + + public static DeclarationScope Current => + CurrentScope.Value ?? throw new DslException("targets and toolchains are declared in a BUILD.csx"); + + /// <summary>Makes <paramref name="scope"/> the file that is running until the result is disposed.</summary> + public static IDisposable Enter(DeclarationScope scope) + { + var previous = CurrentScope.Value; + CurrentScope.Value = scope; + return new Restore(() => CurrentScope.Value = previous); + } + + public static Target Declare(Family family, TargetKind kind, string name, object settings, string file, int line) + { + var scope = Current; + if (settings is null) + { + throw new DslException($"{scope.Place(line)}: '{name}' needs its settings: new() {{ ... }}"); + } + + var label = scope.Claim(name, line); + scope.Targets.Add(new TargetDeclaration(family, kind, name, label, settings, scope.File, line)); + return new Target(label); + } + + public static void DeclareToolchain(Family family, string name, object settings, string file, int line) + { + var scope = Current; + if (settings is null) + { + throw new DslException($"{scope.Place(line)}: the toolchain '{name}' needs its settings"); + } + + var label = scope.Claim(name, line); + scope.Toolchains.Add(new ToolchainDeclaration(family, name, label, settings, scope.File, line)); + } + + private sealed class Restore(Action undo) : IDisposable + { + public void Dispose() => undo(); + } +} diff --git a/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs b/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs new file mode 100644 index 0000000..6a800d7 --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs @@ -0,0 +1,364 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using Progmasoft.Tazel.Dsl.Common; + +namespace Progmasoft.Tazel.Dsl.Module.Prelude; + +/// <summary>What a module says about itself.</summary> +public sealed class ModuleDefinition +{ + /// <summary>The group, as in <c>com.example</c>.</summary> + public string Group { get; init; } = ""; + + /// <summary>The name of the module.</summary> + public string Name { get; init; } = ""; + + /// <summary>The SemVer version.</summary> + public string Version { get; init; } = ""; + + /// <summary>One sentence about the module.</summary> + public string? Description { get; init; } + + /// <summary>Who wrote it.</summary> + public IReadOnlyList<string> Authors { get; init; } = []; + + /// <summary>The SPDX expression of its license.</summary> + public string? License { get; init; } + + /// <summary>Its README; default: README.md.</summary> + public string Readme { get; init; } = "README.md"; + + /// <summary>The Tazel versions it builds with; default: any.</summary> + public TazelVersion? Compatibility { get; init; } +} + +/// <summary>The module of a <c>MODULE.csx</c>.</summary> +public sealed class Module +{ + private Module(ModuleDefinition definition) => Definition = definition; + + /// <summary>What the module says about itself.</summary> + public ModuleDefinition Definition { get; } + + /// <summary>The module of this file.</summary> + public static Module Define(ModuleDefinition definition) + { + ArgumentNullException.ThrowIfNull(definition); + return new Module(definition); + } + + /// <summary>A dependency on a module of Tazel Portal Modules.</summary> + public static Dependency From(ModuleCoordinates coordinates) + { + ArgumentNullException.ThrowIfNull(coordinates); + return new Dependency(coordinates, null); + } +} + +/// <summary>A module of Tazel Portal Modules, by group, name and version.</summary> +public sealed class ModuleCoordinates +{ + /// <summary>The group.</summary> + public string Group { get; init; } = ""; + + /// <summary>The name.</summary> + public string Name { get; init; } = ""; + + /// <summary>The version.</summary> + public string Version { get; init; } = ""; + + /// <summary>The name its labels use instead of <see cref="Name"/>.</summary> + public string? Alias { get; init; } +} + +/// <summary>A module in an archive of this module.</summary> +public sealed class LocalModuleSettings +{ + /// <summary>The name its labels use: <c>@name//:x</c>.</summary> + public string Name { get; init; } = ""; + + /// <summary>The archive, a <c>.tazel.tar.xz</c> file.</summary> + public string Include { get; init; } = ""; + + /// <summary>The SHA-256 of the archive.</summary> + public string? Sha256 { get; init; } + + /// <summary>A <c>.sha256sums</c> file that names the archive.</summary> + public string? Sha256Sums { get; init; } +} + +/// <summary>A module in an archive of this module.</summary> +public static class LocalModule +{ + /// <summary>A dependency on an archive.</summary> + public static Dependency From(LocalModuleSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + return new Dependency(null, settings); + } +} + +/// <summary>A module this module depends on.</summary> +public sealed class Dependency +{ + internal Dependency(ModuleCoordinates? portal, LocalModuleSettings? local) + { + Portal = portal; + Local = local; + } + + /// <summary>The module of Tazel Portal Modules, if it is one.</summary> + public ModuleCoordinates? Portal { get; } + + /// <summary>The archive, if it is one.</summary> + public LocalModuleSettings? Local { get; } +} + +/// <summary>The modules a module depends on.</summary> +public sealed class Dependencies +{ + private Dependencies(IReadOnlyList<Dependency> items) => Items = items; + + /// <summary>The dependencies, in their order.</summary> + public IReadOnlyList<Dependency> Items { get; } + + /// <summary>The dependencies of this module.</summary> + public static Dependencies Define(params Dependency[] items) + { + ArgumentNullException.ThrowIfNull(items); + return new Dependencies(items); + } +} + +/// <summary>Whether and how the module goes to Tazel Portal Modules.</summary> +public sealed class PortalModulesSettings +{ + /// <summary>Whether <c>tazel push</c> may push it; default: false.</summary> + public bool Push { get; init; } + + /// <summary>Files left out of its archive.</summary> + public Files Exclude { get; init; } = Files.None; +} + +/// <summary>Whether and how the module goes to Tazel Portal Modules.</summary> +public sealed class PortalModules +{ + private PortalModules(PortalModulesSettings settings) => Settings = settings; + + /// <summary>The settings.</summary> + public PortalModulesSettings Settings { get; } + + /// <summary>The settings of this module.</summary> + public static PortalModules Define(PortalModulesSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + return new PortalModules(settings); + } +} + +/// <summary>A remote cache or remote execution service.</summary> +public sealed class RemoteSettings +{ + /// <summary>Whether results are read from it; default: true.</summary> + public bool Read { get; init; } = true; + + /// <summary>Whether results are written to it; default: false.</summary> + public bool Write { get; init; } + + /// <summary>The token that signs in.</summary> + public string? Token { get; init; } + + /// <summary>The key that checks what is read.</summary> + public string? PublicKey { get; init; } + + /// <summary>The key that signs what is written.</summary> + public string? SigningKey { get; init; } +} + +/// <summary>A service at a URL.</summary> +public sealed class Remote +{ + private Remote(Uri url, RemoteSettings settings) + { + Url = url; + Settings = settings; + } + + /// <summary>Where the service is.</summary> + public Uri Url { get; } + + /// <summary>How it is used.</summary> + public RemoteSettings Settings { get; } + + /// <summary>The service at <paramref name="url"/>.</summary> + public static Remote From(string url, RemoteSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + if (!Uri.TryCreate(url, UriKind.Absolute, out var parsed) || parsed.Scheme != Uri.UriSchemeHttps) + { + throw new DslException($"'{url}' is not an https URL"); + } + + return new Remote(parsed, settings); + } +} + +/// <summary>The local and remote cache of results.</summary> +public sealed class CacheSettings +{ + /// <summary>Whether results are kept on this machine; default: true.</summary> + public bool Local { get; init; } = true; + + /// <summary>How many results are kept per target; default: 8.</summary> + public int Keep { get; init; } = 8; + + /// <summary>A remote cache; default: none.</summary> + public Remote? Remote { get; init; } +} + +/// <summary>The cache of a module.</summary> +public sealed class Cache +{ + private Cache(CacheSettings settings) => Settings = settings; + + /// <summary>The settings.</summary> + public CacheSettings Settings { get; } + + /// <summary>The cache of this module.</summary> + public static Cache Define(CacheSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + return new Cache(settings); + } +} + +/// <summary>How a build runs.</summary> +public sealed class ExecutionSettings +{ + /// <summary>How many actions run at once; default: the processors.</summary> + public int? Jobs { get; init; } + + /// <summary>How much memory the actions may use together; default: no limit.</summary> + public ByteSize? Memory { get; init; } + + /// <summary>Whether a build goes on after an action failed; default: false.</summary> + public bool KeepGoing { get; init; } + + /// <summary>A remote execution service; default: none.</summary> + public Remote? Remote { get; init; } +} + +/// <summary>How the builds of a module run.</summary> +public sealed class Execution +{ + private Execution(ExecutionSettings settings) => Settings = settings; + + /// <summary>The settings.</summary> + public ExecutionSettings Settings { get; } + + /// <summary>How the builds of this module run.</summary> + public static Execution Define(ExecutionSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + return new Execution(settings); + } +} + +/// <summary>A plugin, from Tazel Portal or from an archive of this module.</summary> +public sealed class PluginReference +{ + internal PluginReference(string? group, string? name, string? version, string? path) + { + Group = group; + Name = name; + Version = version; + Path = path; + } + + /// <summary>The group of a plugin of Tazel Portal.</summary> + public string? Group { get; } + + /// <summary>The name of a plugin of Tazel Portal.</summary> + public string? Name { get; } + + /// <summary>The version; none takes the highest by SemVer.</summary> + public string? Version { get; } + + /// <summary>The archive of a local plugin.</summary> + public string? Path { get; } +} + +/// <summary>A plugin of Tazel Portal.</summary> +public static class Plugin +{ + /// <summary>The plugin <paramref name="group"/>.<paramref name="name"/>, at a version or the highest.</summary> + public static PluginReference From(string group, string name, string? version = null) => + new(group, name, version, null); +} + +/// <summary>A plugin in an archive of this module.</summary> +public static class LocalPlugin +{ + /// <summary>The plugin in the <c>.tazel.tar.xz</c> at <paramref name="path"/>.</summary> + public static PluginReference From(string path) => new(null, null, null, path); +} + +/// <summary>The plugins of a module.</summary> +public sealed class Plugins +{ + private Plugins(IReadOnlyList<PluginReference> items) => Items = items; + + /// <summary>The plugins, in their order.</summary> + public IReadOnlyList<PluginReference> Items { get; } + + /// <summary>The plugins of this module.</summary> + public static Plugins Define(params PluginReference[] items) + { + ArgumentNullException.ThrowIfNull(items); + return new Plugins(items); + } +} + +/// <summary>The toolchains a module registers, in the order they are tried.</summary> +public sealed class Toolchains +{ + private Toolchains(IReadOnlyList<string> labels) => Labels = labels; + + /// <summary>The labels of the toolchains.</summary> + public IReadOnlyList<string> Labels { get; } + + /// <summary>Registers toolchains by label.</summary> + public static Toolchains Define(params string[] labels) + { + ArgumentNullException.ThrowIfNull(labels); + return new Toolchains(labels); + } +} + +/// <summary>What a <c>MODULE.csx</c> sets.</summary> +public sealed class ModuleGlobals +{ + /// <summary>The module.</summary> + public Module? module { get; set; } + + /// <summary>The modules it depends on.</summary> + public Dependencies? dependencies { get; set; } + + /// <summary>Its settings for Tazel Portal Modules.</summary> + public PortalModules? portalModules { get; set; } + + /// <summary>Its cache.</summary> + public Cache? cache { get; set; } + + /// <summary>How its builds run.</summary> + public Execution? execution { get; set; } + + /// <summary>Its plugins.</summary> + public Plugins? plugins { get; set; } + + /// <summary>Its toolchains.</summary> + public Toolchains? toolchains { get; set; } +} diff --git a/src/Progmasoft.Tazel.Dsl/Module/Prelude/TazelVersion.cs b/src/Progmasoft.Tazel.Dsl/Module/Prelude/TazelVersion.cs new file mode 100644 index 0000000..ab75d4a --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Module/Prelude/TazelVersion.cs @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; + +namespace Progmasoft.Tazel.Dsl.Module.Prelude; + +/// <summary>How a <see cref="TazelVersion"/> compares.</summary> +public enum VersionComparison +{ + /// <summary>Only this version.</summary> + Exactly, + + /// <summary>This version or a later one.</summary> + AtLeast, + + /// <summary>A later version.</summary> + GreaterThan, + + /// <summary>This version or an earlier one.</summary> + AtMost, + + /// <summary>An earlier version.</summary> + LessThan, + + /// <summary>From the lower version to the upper one, both included.</summary> + Between, +} + +/// <summary>The Tazel versions a module builds with; PATCH may be left out and is then 0.</summary> +public sealed class TazelVersion +{ + private TazelVersion(VersionComparison comparison, Version lower, Version? upper) + { + Comparison = comparison; + Lower = lower; + Upper = upper; + } + + /// <summary>How the versions compare.</summary> + public VersionComparison Comparison { get; } + + /// <summary>The version, or the lower end of <see cref="VersionComparison.Between"/>.</summary> + public Version Lower { get; } + + /// <summary>The upper end of <see cref="VersionComparison.Between"/>.</summary> + public Version? Upper { get; } + + /// <summary>Only MAJOR.MINOR.PATCH.</summary> + public static TazelVersion Exactly(int major, int minor, int patch = 0) => + new(VersionComparison.Exactly, Make(major, minor, patch), null); + + /// <summary>MAJOR.MINOR.PATCH or later.</summary> + public static TazelVersion AtLeast(int major, int minor, int patch = 0) => + new(VersionComparison.AtLeast, Make(major, minor, patch), null); + + /// <summary>Later than MAJOR.MINOR.PATCH.</summary> + public static TazelVersion GreaterThan(int major, int minor, int patch = 0) => + new(VersionComparison.GreaterThan, Make(major, minor, patch), null); + + /// <summary>MAJOR.MINOR.PATCH or earlier.</summary> + public static TazelVersion AtMost(int major, int minor, int patch = 0) => + new(VersionComparison.AtMost, Make(major, minor, patch), null); + + /// <summary>Earlier than MAJOR.MINOR.PATCH.</summary> + public static TazelVersion LessThan(int major, int minor, int patch = 0) => + new(VersionComparison.LessThan, Make(major, minor, patch), null); + + /// <summary>From MAJOR.MINOR to MAJOR.MINOR, both included.</summary> + public static TazelVersion Between(int major, int minor, int upperMajor, int upperMinor) => + Between(major, minor, 0, upperMajor, upperMinor, 0); + + /// <summary>From MAJOR.MINOR.PATCH to MAJOR.MINOR.PATCH, both included.</summary> + public static TazelVersion Between(int major, int minor, int patch, int upperMajor, int upperMinor, int upperPatch) + { + var lower = Make(major, minor, patch); + var upper = Make(upperMajor, upperMinor, upperPatch); + if (upper < lower) + { + throw new DslException($"TazelVersion.Between: {upper} comes before {lower}"); + } + + return new TazelVersion(VersionComparison.Between, lower, upper); + } + + /// <summary>Whether <paramref name="version"/> is one of these versions.</summary> + public bool Admits(Version version) + { + ArgumentNullException.ThrowIfNull(version); + var compared = Plain(version).CompareTo(Lower); + return Comparison switch + { + VersionComparison.Exactly => compared == 0, + VersionComparison.AtLeast => compared >= 0, + VersionComparison.GreaterThan => compared > 0, + VersionComparison.AtMost => compared <= 0, + VersionComparison.LessThan => compared < 0, + _ => compared >= 0 && Plain(version).CompareTo(Upper) <= 0, + }; + } + + /// <inheritdoc/> + public override string ToString() => Comparison switch + { + VersionComparison.Exactly => $"exactly {Lower}", + VersionComparison.AtLeast => $"{Lower} or later", + VersionComparison.GreaterThan => $"later than {Lower}", + VersionComparison.AtMost => $"{Lower} or earlier", + VersionComparison.LessThan => $"earlier than {Lower}", + _ => $"{Lower} to {Upper}", + }; + + private static Version Plain(Version version) => + new(version.Major, Math.Max(version.Minor, 0), Math.Max(version.Build, 0)); + + private static Version Make(int major, int minor, int patch) + { + if (major < 0 || minor < 0 || patch < 0) + { + throw new DslException($"a Tazel version has no negative parts: {major}.{minor}.{patch}"); + } + + return new Version(major, minor, patch); + } +} diff --git a/src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj b/src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj new file mode 100644 index 0000000..4044ccc --- /dev/null +++ b/src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj @@ -0,0 +1,12 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<!-- The types MODULE.csx and BUILD.csx are written against. --> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <RootNamespace>Progmasoft.Tazel.Dsl</RootNamespace> + </PropertyGroup> + <ItemGroup> + <InternalsVisibleTo Include="tazel" /> + <InternalsVisibleTo Include="Progmasoft.Tazel.Tests" /> + </ItemGroup> +</Project> diff --git a/src/Progmasoft.Tazel/Archive/ModuleArchive.cs b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs new file mode 100644 index 0000000..58835b4 --- /dev/null +++ b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs @@ -0,0 +1,293 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Formats.Tar; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using LzmaNet; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Archive; + +/// <summary> +/// The archive of a module, <c>$group.$module-$version.tazel.tar.xz</c>: the files of the module below one directory +/// of that name less the extension. It is reproducible: entries are sorted, owned by no one, dated at the epoch, and +/// either <c>0644</c> or, for an executable file, <c>0755</c>. +/// </summary> +internal static class ModuleArchive +{ + /// <summary>The extension of an archive.</summary> + public const string Extension = ".tazel.tar.xz"; + + /// <summary>The most an archive may unpack to; a larger one is refused before it fills the disk.</summary> + public const long MaxUnpackedBytes = 1L << 30; + + /// <summary>The most entries an archive may hold.</summary> + public const int MaxEntries = 100_000; + + private const UnixFileMode FileMode = + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead; + + private const UnixFileMode ExecutableMode = FileMode | + UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute; + + private const UnixFileMode DirectoryMode = ExecutableMode | UnixFileMode.UserWrite; + + /// <summary><c>$group.$module-$version</c>, the name of an archive without its extension.</summary> + public static string BaseName(string group, string module, string version) => $"{group}.{module}-{version}"; + + /// <summary> + /// The files of the module at <paramref name="root"/> that go into its archive: every regular file below it, less what + /// starts with a dot (<c>.tazel</c>, <c>.git</c>), the directories of other modules and what + /// <paramref name="excluded"/> matches. + /// </summary> + public static IReadOnlyList<string> Files(string root, Func<string, bool> excluded) + { + ArgumentNullException.ThrowIfNull(excluded); + var found = new List<string>(); + Visit(new DirectoryInfo(root), ""); + found.Sort(StringComparer.Ordinal); + return found; + + void Visit(DirectoryInfo directory, string prefix) + { + foreach (var entry in directory.EnumerateFileSystemInfos().OrderBy(e => e.Name, StringComparer.Ordinal)) + { + if (entry.Name.StartsWith('.')) + { + continue; + } + + var relative = prefix + entry.Name; + if (entry.LinkTarget is not null) + { + throw new ProjectException($"{relative} is a symbolic link; an archive holds only files"); + } + + if (entry is DirectoryInfo child) + { + if (!System.IO.File.Exists(Path.Combine(child.FullName, ModuleFiles.ModuleFile))) + { + Visit(child, relative + "/"); + } + } + else if (!excluded(relative)) + { + found.Add(relative); + } + } + } + } + + /// <summary>Writes <paramref name="files"/> of the module at <paramref name="root"/> below <paramref name="baseName"/>.</summary> + public static void Write(string root, string baseName, string archive, IReadOnlyList<string> files) + { + ArgumentNullException.ThrowIfNull(files); + var directory = Path.GetDirectoryName(Path.GetFullPath(archive))!; + Directory.CreateDirectory(directory); + var temporary = Path.Combine(directory, $".{Path.GetFileName(archive)}.{Guid.NewGuid():N}.partial"); + try + { + using (var output = System.IO.File.Create(temporary)) + using (var xz = new XzCompressStream(output, new XzCompressOptions { Threads = 1 }, leaveOpen: false)) + using (var tar = new TarWriter(xz, TarEntryFormat.Ustar, leaveOpen: false)) + { + foreach (var (path, isDirectory) in PathsAndDirectories(files)) + { + var name = path.Length == 0 ? $"{baseName}/" : isDirectory ? $"{baseName}/{path}/" : $"{baseName}/{path}"; + var entry = new UstarTarEntry(isDirectory ? TarEntryType.Directory : TarEntryType.RegularFile, name) + { + ModificationTime = DateTimeOffset.UnixEpoch, + Uid = 0, + Gid = 0, + UserName = "", + GroupName = "", + }; + var source = Path.Combine(root, path); + entry.Mode = isDirectory ? DirectoryMode : IsExecutable(source) ? ExecutableMode : FileMode; + if (isDirectory) + { + tar.WriteEntry(entry); + } + else + { + using var data = System.IO.File.OpenRead(source); + entry.DataStream = data; + tar.WriteEntry(entry); + } + } + } + + System.IO.File.Move(temporary, archive, overwrite: true); + } + finally + { + System.IO.File.Delete(temporary); + } + } + + /// <summary> + /// Unpacks <paramref name="archive"/> into <paramref name="destination"/>, which must not exist, and returns the + /// directory of the module in it. Every entry must be below one top directory; links, devices, absolute paths and + /// <c>..</c> are refused, as are archives over <see cref="MaxUnpackedBytes"/> or <see cref="MaxEntries"/>. + /// </summary> + public static string Unpack(string archive, string destination) + { + var shown = Path.GetFileName(archive); + var parent = Path.GetDirectoryName(Path.GetFullPath(destination))!; + Directory.CreateDirectory(parent); + var work = Path.Combine(parent, $".unpack-{Guid.NewGuid():N}"); + Directory.CreateDirectory(work); + try + { + string? top = null; + long total = 0; + var entries = 0; + using (var input = System.IO.File.OpenRead(archive)) + using (var xz = new XzDecompressStream(input, new XzDecompressOptions(), leaveOpen: false)) + using (var tar = new TarReader(xz)) + { + while (tar.GetNextEntry() is { } entry) + { + if (++entries > MaxEntries) + { + throw new ProjectException($"{shown} holds more than {MaxEntries} entries"); + } + + var name = entry.Name.TrimEnd('/'); + var parts = name.Split('/'); + if (name.Length == 0 || name.StartsWith('/') || name.Contains('\\', StringComparison.Ordinal) || + parts.Any(part => part is "" or "." or "..")) + { + throw new ProjectException($"{shown}: '{entry.Name}' is not a path inside the archive"); + } + + top ??= parts[0]; + if (parts[0] != top) + { + throw new ProjectException($"{shown}: '{entry.Name}' is not below {top}/"); + } + + var target = Path.Combine(work, Path.Combine(parts)); + switch (entry.EntryType) + { + case TarEntryType.Directory: + Directory.CreateDirectory(target); + break; + case TarEntryType.RegularFile or TarEntryType.V7RegularFile: + total += entry.Length; + if (total > MaxUnpackedBytes) + { + throw new ProjectException($"{shown} unpacks to more than {MaxUnpackedBytes} bytes"); + } + + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + entry.ExtractToFile(target, overwrite: false); + break; + default: + throw new ProjectException($"{shown}: '{entry.Name}' is a {entry.EntryType}; an archive holds only files"); + } + } + } + + if (top is null) + { + throw new ProjectException($"{shown} is empty"); + } + + if (!System.IO.File.Exists(Path.Combine(work, top, ModuleFiles.ModuleFile))) + { + throw new ProjectException($"{shown} has no {top}/{ModuleFiles.ModuleFile}"); + } + + Directory.Move(work, destination); + return Path.Combine(destination, top); + } + catch (Exception error) when (error is IOException or InvalidDataException or FormatException) + { + throw new ProjectException($"{shown} could not be unpacked: {error.Message}", error); + } + finally + { + if (Directory.Exists(work)) + { + Directory.Delete(work, recursive: true); + } + } + } + + private static bool IsExecutable(string file) => + !OperatingSystem.IsWindows() && + (System.IO.File.GetUnixFileMode(file) & UnixFileMode.UserExecute) != 0; + + private static IEnumerable<(string Path, bool IsDirectory)> PathsAndDirectories(IReadOnlyList<string> files) + { + var directories = new SortedSet<string>(StringComparer.Ordinal) { "" }; + foreach (var file in files) + { + var parts = file.Split('/'); + for (var depth = 1; depth < parts.Length; depth++) + { + directories.Add(string.Join('/', parts.Take(depth))); + } + } + + return directories.Select(d => (d, true)).Concat(files.Select(f => (f, false))) + .OrderBy(entry => entry.Item1, StringComparer.Ordinal); + } +} + +/// <summary>The SHA-256 of an archive and the <c>.sha256sums</c> file beside it, as <c>sha256sum</c> writes it.</summary> +internal static class Sha256Sums +{ + /// <summary>The SHA-256 of <paramref name="file"/> in lower-case hexadecimal.</summary> + public static string Sha256(string file) + { + using var stream = System.IO.File.OpenRead(file); + return Convert.ToHexStringLower(SHA256.HashData(stream)); + } + + /// <summary>The line of a <c>.sha256sums</c> file for <paramref name="file"/>.</summary> + public static string SumsLine(string file) => $"{Sha256(file)} {Path.GetFileName(file)}\n"; + + /// <summary> + /// The SHA-256 that the <c>.sha256sums</c> text <paramref name="sums"/> gives for <paramref name="name"/>. Lines are + /// <c><sha256> <name></c> or <c><sha256> *<name></c>; blank lines are skipped and any other + /// line is an error. + /// </summary> + public static string? SumFor(string sums, string name, string shown) + { + ArgumentNullException.ThrowIfNull(sums); + string? found = null; + var number = 0; + foreach (var raw in sums.Split('\n')) + { + number++; + var line = raw.TrimEnd('\r'); + if (line.Trim().Length == 0) + { + continue; + } + + if (line.Length < 67 || !line[..64].All(Uri.IsHexDigit) || line[64] != ' ' || line[65] is not (' ' or '*')) + { + throw new ProjectException($"{shown}:{number}: not a line of sha256sum: '{line}'"); + } + + if (line[66..] == name) + { + if (found is not null) + { + throw new ProjectException($"{shown} lists {name} twice"); + } + + found = line[..64].ToLowerInvariant(); + } + } + + return found; + } +} diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs new file mode 100644 index 0000000..306f267 --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -0,0 +1,406 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Output; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>A command line that cannot be taken, with a hint when there is one.</summary> +internal sealed class CommandLineException : Exception +{ + public CommandLineException(string message) + : base(message) + { + } + + public CommandLineException() + { + } + + public CommandLineException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// <summary>How Tazel prints, for every command.</summary> +internal sealed record OutputOptions(When Color, When Progress, bool Quiet); + +/// <summary>What <c>build</c>, <c>run</c> and <c>test</c> take beyond their labels.</summary> +internal sealed record BuildFlags +{ + public BuildMode? Mode { get; init; } + + public Platform? Platform { get; init; } + + public int? Jobs { get; init; } + + public bool KeepGoing { get; init; } + + public List<string> FeaturesOn { get; } = []; + + public List<string> FeaturesOff { get; } = []; + + public List<string> CompilerOptions { get; } = []; + + public List<string> CCompilerOptions { get; } = []; + + public List<string> CppCompilerOptions { get; } = []; + + public List<string> LinkerOptions { get; } = []; + + public List<string> ZigCompilerOptions { get; } = []; +} + +/// <summary>A command line, read into what it asks for; later stages do not look at its text again.</summary> +internal abstract record Command(OutputOptions Output); + +internal sealed record BuildCommand(OutputOptions Output, IReadOnlyList<string> Labels, BuildFlags Flags) : Command(Output); + +internal sealed record TestCommand(OutputOptions Output, IReadOnlyList<string> Labels, BuildFlags Flags) : Command(Output); + +internal sealed record RunCommand(OutputOptions Output, string? Label, BuildFlags Flags, IReadOnlyList<string> Arguments) + : Command(Output); + +internal sealed record CleanCommand(OutputOptions Output, bool Expunge) : Command(Output); + +internal sealed record PackageCommand(OutputOptions Output) : Command(Output); + +internal sealed record CustomCommandLine(OutputOptions Output, IReadOnlyList<string> Words) : Command(Output); + +internal sealed record VersionCommand(OutputOptions Output) : Command(Output); + +internal sealed record HelpCommand(OutputOptions Output, string? Topic) : Command(Output); + +internal sealed record DaemonCommand(OutputOptions Output, string Action) : Command(Output); + +/// <summary> +/// Reads command lines by hand, into typed values. Long options take their value after whitespace, <c>=</c> or +/// <c>:</c>; short options also joined (<c>-hbuild</c> is not an option, as <c>-h</c> takes none). A list is +/// accepted only after <c>=</c> or <c>:</c>, separated by commas with no spaces; <c>\,</c> is a comma of a value. +/// Options may stand anywhere before <c>--</c>. +/// </summary> +internal static class CommandLine +{ + /// <summary>The commands, as <c>tazel help</c> lists them.</summary> + public static IReadOnlyList<string> Commands { get; } = + ["build", "run", "test", "clean", "package", "custom", "version", "help", "dotnet"]; + + private enum Kind + { + Flag, + Value, + List, + } + + private sealed record Option(string Long, Kind Kind, IReadOnlyList<string>? Values, params string[] Commands); + + private static readonly string[] Building = ["build", "run", "test"]; + + private static readonly Option[] Options = + [ + new("color", Kind.Value, ["always", "auto", "never"]), + new("progress", Kind.Value, ["always", "auto", "never"]), + new("quiet", Kind.Flag, null), + new("help", Kind.Flag, null), + new("platform", Kind.Value, Platforms.Names, Building), + new("mode", Kind.Value, ["debug", "release"], Building), + new("jobs", Kind.Value, null, Building), + new("keep-going", Kind.Flag, null, Building), + new("feature", Kind.List, null, Building), + new("no-feature", Kind.List, null, Building), + new("compiler-options", Kind.List, null, Building), + new("c-compiler-options", Kind.List, null, Building), + new("cpp-compiler-options", Kind.List, null, Building), + new("linker-options", Kind.List, null, Building), + new("zig-compiler-options", Kind.List, null, Building), + new("expunge", Kind.Flag, null, "clean"), + ]; + + /// <summary>Reads <paramref name="arguments"/>.</summary> + public static Command Parse(IReadOnlyList<string> arguments) + { + ArgumentNullException.ThrowIfNull(arguments); + string? command = null; + var positional = new List<string>(); + var afterDashes = new List<string>(); + var seen = new List<(Option Option, List<string> Values, string Written)>(); + var index = 0; + while (index < arguments.Count) + { + var argument = arguments[index++]; + if (command == "custom") + { + // Everything after `tazel custom` belongs to the custom command, its options too. + positional.Add(argument); + continue; + } + + if (argument == "--") + { + afterDashes.AddRange(arguments.Skip(index)); + break; + } + + if (argument.StartsWith("--", StringComparison.Ordinal)) + { + ReadLong(argument, arguments, ref index, seen); + } + else if (argument.StartsWith('-') && argument.Length > 1) + { + ReadShort(argument, seen); + } + else if (command is null) + { + command = Commands.Contains(argument, StringComparer.Ordinal) ? argument : throw UnknownCommand(argument); + } + else + { + positional.Add(argument); + } + } + + command ??= "help"; + foreach (var (option, _, written) in seen) + { + if (option.Commands.Length > 0 && !option.Commands.Contains(command, StringComparer.Ordinal)) + { + throw new CommandLineException($"{written} is not an option of tazel {command}"); + } + } + + var output = new OutputOptions( + ParseWhen(Last(seen, "color")) ?? When.Auto, + ParseWhen(Last(seen, "progress")) ?? When.Auto, + seen.Any(entry => entry.Option.Long == "quiet")); + if (seen.Any(entry => entry.Option.Long == "help") && command != "help") + { + return new HelpCommand(output, command); + } + + if (afterDashes.Count > 0 && command != "run") + { + throw new CommandLineException($"tazel {command} takes nothing after --; only tazel run passes arguments on"); + } + + switch (command) + { + case "build": + return new BuildCommand(output, positional, Flags(seen)); + case "test": + return new TestCommand(output, positional, Flags(seen)); + case "run": + if (positional.Count > 1) + { + throw new CommandLineException( + $"tazel run takes one target; the program's own arguments go after --: tazel run {positional[0]} -- {string.Join(' ', positional.Skip(1))}"); + } + + return new RunCommand(output, positional.FirstOrDefault(), Flags(seen), afterDashes); + case "clean": + NoPositional(command, positional); + return new CleanCommand(output, seen.Any(entry => entry.Option.Long == "expunge")); + case "package": + NoPositional(command, positional); + return new PackageCommand(output); + case "custom": + return positional.Count == 0 + ? throw new CommandLineException("tazel custom needs the name of a command of tazel_custom.txt") + : new CustomCommandLine(output, positional); + case "version": + NoPositional(command, positional); + return new VersionCommand(output); + case "dotnet": + var actions = new[] { "start-daemon", "restart-daemon", "stop-daemon" }; + if (positional.Count != 1 || !actions.Contains(positional[0], StringComparer.Ordinal)) + { + var near = positional.Count == 1 ? Suggestions.Nearest(positional[0], actions) : null; + throw new CommandLineException( + $"tazel dotnet takes start-daemon, restart-daemon or stop-daemon{(near is null ? "" : $"; did you mean {near}?")}"); + } + + return new DaemonCommand(output, positional[0]); + default: + return positional.Count > 1 + ? throw new CommandLineException("tazel help takes one command") + : new HelpCommand(output, positional.FirstOrDefault()); + } + } + + /// <summary>Splits a list at commas; <c>\,</c> is a comma of a value.</summary> + public static IReadOnlyList<string> SplitList(string text) + { + ArgumentNullException.ThrowIfNull(text); + var items = new List<string>(); + var current = new StringBuilder(); + for (var i = 0; i < text.Length; i++) + { + if (text[i] == '\\' && i + 1 < text.Length && text[i + 1] == ',') + { + current.Append(','); + i++; + } + else if (text[i] == ',') + { + items.Add(current.ToString()); + current.Clear(); + } + else + { + current.Append(text[i]); + } + } + + items.Add(current.ToString()); + return items; + } + + private static void ReadLong( + string argument, IReadOnlyList<string> arguments, ref int index, List<(Option, List<string>, string)> seen) + { + var body = argument[2..]; + var separator = body.IndexOfAny(['=', ':']); + var name = separator < 0 ? body : body[..separator]; + var option = Options.FirstOrDefault(o => o.Long == name); + if (option is null) + { + var near = Suggestions.Nearest(name, Options.Select(o => o.Long)); + var rest = separator < 0 ? "" : body[separator..]; + throw new CommandLineException( + $"--{name} is not an option{(near is null ? "" : $"; did you mean --{near}{rest}?")}"); + } + + List<string> values; + if (option.Kind == Kind.Flag) + { + if (separator >= 0) + { + throw new CommandLineException($"--{name} takes no value"); + } + + values = []; + } + else if (separator >= 0) + { + var text = body[(separator + 1)..]; + values = option.Kind == Kind.List ? [.. SplitList(text)] : [text]; + Check(option, values, $"--{name}{body[separator]}"); + } + else + { + if (index >= arguments.Count) + { + throw new CommandLineException($"--{name} needs a value"); + } + + // Whitespace gives one value, whatever it holds. + values = [arguments[index++]]; + Check(option, values, $"--{name} "); + } + + if (values.Any(value => value.Length == 0)) + { + throw new CommandLineException($"--{name} has an empty value"); + } + + seen.Add((option, values, $"--{name}")); + } + + private static void ReadShort(string argument, List<(Option, List<string>, string)> seen) + { + if (argument == "-h") + { + seen.Add((Options.First(o => o.Long == "help"), [], "-h")); + return; + } + + throw new CommandLineException($"{argument} is not an option; tazel help lists them"); + } + + private static void Check(Option option, List<string> values, string written) + { + if (option.Values is null) + { + return; + } + + foreach (var value in values) + { + if (!option.Values.Contains(value, StringComparer.Ordinal)) + { + var near = Suggestions.Nearest(value, option.Values); + throw new CommandLineException( + $"--{option.Long} takes {string.Join(", ", option.Values)}, not '{value}'" + + (near is null ? "" : $"; did you mean {written}{near}?")); + } + } + } + + private static string? Last(List<(Option Option, List<string> Values, string)> seen, string name) => + seen.LastOrDefault(entry => entry.Option.Long == name).Values?.LastOrDefault(); + + private static IEnumerable<string> All(List<(Option Option, List<string> Values, string)> seen, string name) => + seen.Where(entry => entry.Option.Long == name).SelectMany(entry => entry.Values); + + private static When? ParseWhen(string? text) => text switch + { + "always" => When.Always, + "never" => When.Never, + "auto" => When.Auto, + _ => null, + }; + + private static BuildFlags Flags(List<(Option Option, List<string> Values, string)> seen) + { + int? jobs = null; + if (Last(seen, "jobs") is { } jobsText) + { + jobs = int.TryParse(jobsText, NumberStyles.None, CultureInfo.InvariantCulture, out var parsed) && parsed is > 0 and <= 4096 + ? parsed + : throw new CommandLineException($"--jobs takes a number from 1 to 4096, not '{jobsText}'"); + } + + Platform? platform = Last(seen, "platform") is { } name && Platforms.TryParse(name, out var found) ? found : null; + var flags = new BuildFlags + { + Mode = Last(seen, "mode") switch + { + "debug" => BuildMode.Debug, + "release" => BuildMode.Release, + _ => null, + }, + Platform = platform, + Jobs = jobs, + KeepGoing = seen.Any(entry => entry.Option.Long == "keep-going"), + }; + flags.FeaturesOn.AddRange(All(seen, "feature")); + flags.FeaturesOff.AddRange(All(seen, "no-feature")); + flags.CompilerOptions.AddRange(All(seen, "compiler-options")); + flags.CCompilerOptions.AddRange(All(seen, "c-compiler-options")); + flags.CppCompilerOptions.AddRange(All(seen, "cpp-compiler-options")); + flags.LinkerOptions.AddRange(All(seen, "linker-options")); + flags.ZigCompilerOptions.AddRange(All(seen, "zig-compiler-options")); + return flags; + } + + private static void NoPositional(string command, List<string> positional) + { + if (positional.Count > 0) + { + throw new CommandLineException($"tazel {command} takes no '{positional[0]}'"); + } + } + + private static CommandLineException UnknownCommand(string word) + { + var near = Suggestions.Nearest(word, Commands); + return new CommandLineException( + near is null ? $"'{word}' is not a command of tazel; tazel help lists them" : $"'{word}' is not a command of tazel; did you mean tazel {near}?"); + } +} diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs new file mode 100644 index 0000000..c44e801 --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -0,0 +1,290 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Dsl.Custom; +using Progmasoft.Tazel.Dsl.Custom.Parser; +using Progmasoft.Tazel.Dsl.Options; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>Carries out a command line read by <see cref="CommandLine"/>.</summary> +internal sealed class Commands(Reporter reporter, string workingDirectory) +{ + /// <summary>The version of this Tazel.</summary> + public static Version TazelVersion { get; } = + typeof(Commands).Assembly.GetName().Version is { } version ? new Version(version.Major, version.Minor, version.Build) : new Version(0, 1, 0); + + /// <summary>Runs <paramref name="command"/>; the result is the exit status of tazel.</summary> + public async Task<int> RunAsync(Command command, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(command); + switch (command) + { + case VersionCommand: + reporter.Plain($"tazel {TazelVersion.ToString(3)} (.NET {Environment.Version}, {Host.Platform.Name()})"); + return 0; + case HelpCommand help: + reporter.Plain(Help.Text(help.Topic)); + return 0; + case DaemonCommand daemon: + reporter.Error($"tazel dotnet {daemon.Action}: this Tazel runs every command in a process of its own and has no daemon"); + return 1; + case CleanCommand clean: + return Clean(clean); + case PackageCommand: + return await PackageAsync().ConfigureAwait(false); + case CustomCommandLine custom: + return Custom(custom); + case BuildCommand build: + return await BuildAsync(build.Labels, build.Flags, BuildKind.Build, null, cancel).ConfigureAwait(false); + case TestCommand test: + return await BuildAsync(test.Labels, test.Flags, BuildKind.Test, null, cancel).ConfigureAwait(false); + case RunCommand run: + return await BuildAsync(run.Label is null ? [] : [run.Label], run.Flags, BuildKind.Run, run.Arguments, cancel) + .ConfigureAwait(false); + default: + throw new InvalidOperationException($"no handler for {command.GetType().Name}"); + } + } + + private enum BuildKind + { + Build, + Test, + Run, + } + + /// <summary> + /// Stops a command that would run what a project brings when a sandbox is asked for: this Tazel has no MicroVM to + /// start, so nothing runs rather than run on the host. + /// </summary> + private void RefuseWithoutSandbox() + { + var (_, file) = TazelOptionsFile.Effective(workingDirectory); + if (file is not null) + { + throw new ProjectException( + $"{file} asks for sandboxing-with-microvm, and this Tazel has no MicroVM to start, so nothing ran; " + + "set it to false to run without the sandbox"); + } + } + + /// <summary>Says which settings of MODULE.csx this Tazel reads but does not act on, so none is taken for granted.</summary> + private void WarnAboutWhatThisTazelDoesNotDo(Dsl.Module.Prelude.ModuleGlobals globals) + { + if (globals.cache?.Settings.Remote is { } cache) + { + reporter.Warning($"MODULE.csx names the remote cache {cache.Url}; this Tazel uses the cache on this machine only"); + } + + if (globals.execution?.Settings.Remote is { } remote) + { + reporter.Warning($"MODULE.csx names the remote execution {remote.Url}; this Tazel runs every action on this machine"); + } + + if (globals.execution?.Settings.Memory is not null) + { + reporter.Warning("MODULE.csx sets Execution.Memory; this Tazel limits the actions by Jobs only"); + } + + if (globals.plugins?.Items.Count > 0) + { + reporter.Warning("MODULE.csx names plugins; this Tazel loads no plugins"); + } + } + + private int Clean(CleanCommand clean) + { + var root = ModuleFiles.FindRoot(workingDirectory); + var state = Path.Combine(root, ModuleFiles.StateDirectory); + var removed = clean.Expunge + ? [state] + : new[] { "out", "testlogs", "zig-cache", "package" }.Select(name => Path.Combine(state, name)).ToArray(); + foreach (var directory in removed.Where(Directory.Exists)) + { + Directory.Delete(directory, recursive: true); + } + + reporter.Success(clean.Expunge ? $"removed {state}" : "removed the outputs"); + return 0; + } + + private async Task<int> PackageAsync() + { + RefuseWithoutSandbox(); + var module = await Workspace.LoadMainModuleAsync(workingDirectory, TazelVersion).ConfigureAwait(false); + var exclude = module.Globals.portalModules?.Settings.Exclude ?? Files.None; + var files = ModuleArchive.Files(module.Root, relative => exclude.Items.Any(item => + item.Path is { } path ? path == relative : FileSets.Matches(item.Glob!.Pattern, relative) && + !item.Glob.Exclude.Any(pattern => FileSets.Matches(pattern, relative)))); + var info = module.Info; + var baseName = ModuleArchive.BaseName(info.Group, info.Name, info.Version.ToNormalizedString()); + var archive = Path.Combine(module.Root, ModuleFiles.StateDirectory, "package", baseName + ModuleArchive.Extension); + ModuleArchive.Write(module.Root, baseName, archive, files); + await File.WriteAllTextAsync(archive + ".sha256sums", Sha256Sums.SumsLine(archive)).ConfigureAwait(false); + reporter.Success($"wrote {FileSets.ToRoot(archive, module.Root)} ({files.Count} files) and its .sha256sums"); + return 0; + } + + private int Custom(CustomCommandLine custom) + { + RefuseWithoutSandbox(); + var file = Path.Combine(workingDirectory, CustomCommandFiles.FileName); + if (!File.Exists(file)) + { + throw new CustomCommandsException($"there is no {CustomCommandFiles.FileName} in {workingDirectory}"); + } + + var commands = CustomParser.Parse(File.ReadAllText(file)); + if (custom.Words.Count > CustomCommandFiles.MaxArguments) + { + throw new CommandLineException($"tazel custom takes at most {CustomCommandFiles.MaxArguments} words"); + } + + var match = commands.Matching(custom.Words) ?? throw new CustomCommandsException( + $"{CustomCommandFiles.FileName} has no command '{string.Join(' ', custom.Words.TakeWhile(w => w != CustomCommandFiles.NameEnd))}'" + + (Suggestions.Nearest(string.Join(' ', custom.Words), commands.Select(c => c.Name)) is { } near ? $"; did you mean '{near}'?" : "")); + var (command, arguments) = match; + if (arguments.Count < command.Required) + { + throw new CommandLineException($"'{command.Name}' needs {command.Required} arguments, and {arguments.Count} were given"); + } + + if (arguments.Count > command.Required && !command.TakesAll) + { + throw new CommandLineException($"'{command.Name}' takes {command.Required} arguments, and {arguments.Count} were given"); + } + + var environment = Processes.Inherited(); + foreach (var step in command.Steps) + { + var started = step switch + { + CustomStep.Program program => program.Expanded(arguments), + CustomStep.Shell shell => shell.Started(OperatingSystem.IsWindows()), + _ => throw new InvalidOperationException("a step of no kind"), + }; + var found = Host.Which(started[0]) ?? throw new CustomCommandsException( + $"'{command.Name}': the program '{started[0]}' is not found"); + var status = Processes.RunAttached([found, .. started.Skip(1)], workingDirectory, environment); + if (status != 0) + { + return status; + } + } + + return 0; + } + + private async Task<int> BuildAsync( + IReadOnlyList<string> labels, BuildFlags flags, BuildKind kind, IReadOnlyList<string>? programArguments, + CancellationToken cancel) + { + RefuseWithoutSandbox(); + var (options, _) = TazelOptionsFile.Effective(workingDirectory); + var platform = flags.Platform ?? options.Platform ?? Host.Platform; + var mode = flags.Mode ?? BuildMode.Debug; + reporter.Status($"loading the module for {platform.Name()}, {mode.ToString().ToLowerInvariant()}"); + var workspace = await Workspace.LoadAsync(workingDirectory, new BuildContext(mode, platform), TazelVersion) + .ConfigureAwait(false); + WarnAboutWhatThisTazelDoesNotDo(workspace.Main.Globals); + var execution = workspace.Main.Globals.execution?.Settings; + var buildOptions = new BuildOptions + { + Mode = mode, + Platform = platform, + Jobs = flags.Jobs ?? execution?.Jobs ?? Environment.ProcessorCount, + KeepGoing = flags.KeepGoing || (execution?.KeepGoing ?? false), + FeaturesOn = flags.FeaturesOn, + FeaturesOff = flags.FeaturesOff, + CompilerOptions = flags.CompilerOptions, + CCompilerOptions = flags.CCompilerOptions, + CppCompilerOptions = flags.CppCompilerOptions, + LinkerOptions = flags.LinkerOptions, + ZigCompilerOptions = flags.ZigCompilerOptions, + }; + + var selector = new Selector(workspace, platform); + var selected = kind switch + { + BuildKind.Test => selector.Select(labels, workingDirectory, target => target.Kind == TargetKind.Test, "a test"), + BuildKind.Run => selector.Select(labels, workingDirectory, target => target.IsRunnable, "an executable or a test"), + _ => selector.Select(labels, workingDirectory, _ => true, "a target"), + }; + if (kind == BuildKind.Run && selected.Count != 1) + { + throw new ProjectException(selected.Count == 0 + ? "tazel run found no executable to run; name one: tazel run //dir:name" + : $"tazel run runs one program, and these are {selected.Count}: {string.Join(", ", selected.Select(t => t.Label))}"); + } + + if (selector.Skipped > 0) + { + reporter.Status($"left out {selector.Skipped} target{(selector.Skipped == 1 ? "" : "s")} that do not build for {platform.Name()}"); + } + + var chooser = new ToolchainChooser(workspace, platform); + var planner = new Planner(workspace, buildOptions, chooser); + var planned = selected.Select(target => (Target: target, Products: planner.Plan(target))).ToList(); + planner.CheckCommandLineFeatures(chooser.UsedCC); + var goals = planned.Select(entry => entry.Products.Main).OfType<BuildAction>().Distinct().ToList(); + reporter.Status($"building {selected.Count} target{(selected.Count == 1 ? "" : "s")}"); + var digests = new Digests(); + var cacheSettings = workspace.Main.Globals.cache?.Settings; + var executor = new Executor(buildOptions.Jobs, buildOptions.KeepGoing || kind == BuildKind.Test, + new ActionCache(digests, enabled: cacheSettings?.Local ?? true), reporter); + var built = await executor.RunAsync(goals, cancel).ConfigureAwait(false); + switch (kind) + { + case BuildKind.Test: + var tests = planned.Select(entry => (entry.Target, entry.Products, + Built: entry.Products.Main is { } main && executor.Succeeded(main))).ToList(); + var outcomes = await new TestRunner(planner.Layout, buildOptions.Jobs, reporter).RunAsync(tests, cancel) + .ConfigureAwait(false); + reporter.TestSummary(outcomes); + return outcomes.All(outcome => outcome.Status is TestStatus.Passed or TestStatus.Flaky) ? 0 : 1; + case BuildKind.Run: + if (!built) + { + return 1; + } + + var (target, products) = planned[0]; + var runfiles = Runfiles.Prepare(target, products, planner.Layout); + var environment = Processes.Inherited(); + var settings = (IRunSettings)target.Settings; + foreach (var (name, value) in settings.EnvironmentVariables) + { + environment[name] = value; + } + + Runfiles.AddLibraryPath(environment, products, planner.Layout); + var command = new List<string> { planner.Layout.Full(products.Executable!) }; + command.AddRange(settings.Arguments); + command.AddRange(programArguments ?? []); + return Processes.RunAttached(command, runfiles, environment); + default: + if (!built) + { + reporter.Error($"{executor.Failed} action{(executor.Failed == 1 ? "" : "s")} failed"); + return 1; + } + + reporter.Success($"built {selected.Count} target{(selected.Count == 1 ? "" : "s")}"); + return 0; + } + } +} diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs new file mode 100644 index 0000000..327c812 --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -0,0 +1,120 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System.Collections.Generic; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>What <c>tazel help</c> prints.</summary> +internal static class Help +{ + private const string BuildOptions = """ + --mode debug|release debug (the default) or optimized + --platform <name> the platform to build for; default: tazel_options.txt, else this machine's + --jobs <n> how many actions run at once; default: MODULE.csx, else the processors + --keep-going go on with what does not depend on a failed action + --feature <name> turn a toolchain feature on for every target + --no-feature <name> turn a toolchain feature off for every target + --compiler-options <option> for every C, C++, Objective-C and Objective-C++ file + --c-compiler-options <option> for .c and .m files + --cpp-compiler-options <opt> for .cpp, .cc, .cxx and .mm files + --linker-options <option> for every link + --zig-compiler-options <opt> for every zig command + A list of values goes after = or : without spaces (--feature=asan,lto); \, is a comma of a value. + """; + + private static readonly Dictionary<string, string> Topics = new(System.StringComparer.Ordinal) + { + ["build"] = $""" + tazel build [labels] [options] + + Builds the targets of the labels: //dir:name, //:name, :name, //dir/... or //...; without a label, the + package of the current directory. //... leaves out targets tagged manual and those that do not build for + the platform. + + {BuildOptions} + """, + ["test"] = $""" + tazel test [labels] [options] + + Builds the tests of the labels and runs each in its runfiles directory, with its own TEST_TMPDIR and a + timeout from its TestSize; a flaky test is run up to three times. Logs go to .tazel/testlogs. + + {BuildOptions} + """, + ["run"] = $""" + tazel run <label> [options] [-- arguments] + + Builds one executable or test and runs it in its runfiles directory, with Tazel's environment and the + program's EnvironmentVariables; Arguments and what follows -- are passed to it. + + {BuildOptions} + """, + ["clean"] = """ + tazel clean [--expunge] + + Removes the outputs of every platform and mode, the test logs and zig's cache; --expunge removes all of + .tazel, the unpacked dependencies too. + """, + ["package"] = """ + tazel package + + Writes the archive of the module, $group.$module-$version.tazel.tar.xz, and its .sha256sums to + .tazel/package. The files of PortalModules' Exclude are left out. + """, + ["custom"] = """ + tazel custom <name> [arguments] + + Runs a command of the tazel_custom.txt of the current directory. The longest name that fits wins; -- ends + the name, and what follows is arguments. + """, + ["version"] = """ + tazel version + + Prints the version of Tazel. + """, + ["help"] = """ + tazel help [command] + + Prints what Tazel can do, or what one command does. + """, + ["dotnet"] = """ + tazel dotnet start-daemon|restart-daemon|stop-daemon + + The daemon that keeps the .NET runtime of Tazel warm between commands. + """, + }; + + /// <summary>The help of <paramref name="topic"/>, or the general help.</summary> + public static string Text(string? topic) + { + if (topic is not null) + { + return Topics.TryGetValue(topic, out var text) + ? text.TrimEnd() + : throw new CommandLineException( + $"'{topic}' is not a command of tazel{(Suggestions.Nearest(topic, Topics.Keys) is { } near ? $"; did you mean {near}?" : "")}"); + } + + return """ + Tazel builds C, C++, Objective-C, Objective-C++ and Zig. A module has a MODULE.csx at its root and a + BUILD.csx in each package; targets are named by labels such as //app:greeter. + + Commands: + build build targets + test build and run tests + run build and run one program + clean remove what builds made + package write the archive of the module + custom run a command of tazel_custom.txt + version print the version + help print help; tazel help <command> for one command + + Options of every command: + --color always|auto|never colors; default: auto + --progress always|auto|never the [done/total] counter; default: auto + --quiet only problems and the program's own output + --help, -h the help of the command + """; + } +} diff --git a/src/Progmasoft.Tazel/Cli/Selector.cs b/src/Progmasoft.Tazel/Cli/Selector.cs new file mode 100644 index 0000000..43583a2 --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/Selector.cs @@ -0,0 +1,169 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Linq; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Label; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>Which targets a command line names.</summary> +internal sealed class Selector(Workspace workspace, Platform platform) +{ + private readonly Dictionary<ProjectTarget, string?> _incompatible = []; + + /// <summary>How many targets the patterns left out because they do not build for the platform.</summary> + public int Skipped { get; private set; } + + /// <summary> + /// The targets of <paramref name="labels"/>, from the package of <paramref name="directory"/>; those that + /// <paramref name="wanted"/> refuses are left out of patterns and are an error when named. + /// </summary> + public List<ProjectTarget> Select( + IReadOnlyList<string> labels, string directory, Func<ProjectTarget, bool> wanted, string kind) + { + ArgumentNullException.ThrowIfNull(labels); + ArgumentNullException.ThrowIfNull(wanted); + var current = CurrentPackage(directory); + var selected = new List<ProjectTarget>(); + if (labels.Count == 0) + { + if (current is null) + { + throw new ProjectException("the current directory is in no package; name targets with labels such as //..."); + } + + AddPattern(selected, target => target.Label.Package == current, wanted); + return selected; + } + + foreach (var text in labels) + { + Selection selection; + try + { + selection = Labels.Selection(text, current ?? PackageId.Root); + } + catch (LabelException error) + { + throw new ProjectException(error.Message, error); + } + + switch (selection) + { + case TargetLabel label: + if (!workspace.Targets.TryGetValue(label, out var target)) + { + var package = workspace.Packages.Contains(label.Package) + ? $"its package has no target '{label.Name}'" + : $"there is no package {label.Package}"; + throw new ProjectException($"{label} is not a target: {package}"); + } + + if (!wanted(target)) + { + throw new ProjectException($"{label} is not {kind}"); + } + + if (Incompatibility(target) is { } reason) + { + throw new ProjectException($"{label} does not build for {platform.Name()}: {reason}"); + } + + if (!selected.Contains(target)) + { + selected.Add(target); + } + + break; + case PackagePattern pattern: + if (!workspace.Packages.Any(pattern.Covers)) + { + throw new ProjectException($"{pattern} names no package"); + } + + AddPattern(selected, target => pattern.Covers(target.Label.Package), wanted); + break; + } + } + + return selected; + } + + /// <summary>Why <paramref name="target"/> does not build for the platform, or null when it does.</summary> + public string? Incompatibility(ProjectTarget target) + { + if (_incompatible.TryGetValue(target, out var known)) + { + return known; + } + + string? reason = null; + if (!target.BuildsFor(platform)) + { + reason = $"its TargetConstraints are {string.Join(", ", target.Constraints.Select(p => p.Name()))}" + + (target.Family == Family.ObjectiveC && target.Settings.TargetConstraints.Count == 0 + ? " (the default of Objective-C targets)" + : ""); + } + else + { + foreach (var dependency in target.Dependencies.Concat(target.ZigImports.Values)) + { + if (Incompatibility(dependency) is not null) + { + reason = $"it depends on {dependency.Label}, which does not"; + break; + } + } + } + + _incompatible[target] = reason; + return reason; + } + + private void AddPattern(List<ProjectTarget> selected, Func<ProjectTarget, bool> covered, Func<ProjectTarget, bool> wanted) + { + foreach (var target in workspace.Targets.Values.Where(covered).OrderBy(t => t.Label.ToString(), StringComparer.Ordinal)) + { + if (target.IsManual || !wanted(target) || selected.Contains(target)) + { + continue; + } + + if (Incompatibility(target) is not null) + { + Skipped++; + continue; + } + + selected.Add(target); + } + } + + private PackageId? CurrentPackage(string directory) + { + var relative = FileSets.ToRoot(System.IO.Path.GetFullPath(directory), workspace.Main.Root); + var path = relative == "." ? "" : relative; + while (true) + { + var id = new PackageId(null, path); + if (workspace.Packages.Contains(id)) + { + return id; + } + + if (path.Length == 0) + { + return null; + } + + var slash = path.LastIndexOf('/'); + path = slash < 0 ? "" : path[..slash]; + } + } +} diff --git a/src/Progmasoft.Tazel/Cli/Suggestions.cs b/src/Progmasoft.Tazel/Cli/Suggestions.cs new file mode 100644 index 0000000..8976a0f --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/Suggestions.cs @@ -0,0 +1,53 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>"Did you mean" hints for what was misspelt.</summary> +internal static class Suggestions +{ + /// <summary>The edits between two words: insertions, deletions, substitutions and swaps of neighbours.</summary> + public static int Distance(string a, string b) + { + ArgumentNullException.ThrowIfNull(a); + ArgumentNullException.ThrowIfNull(b); + var d = new int[a.Length + 1, b.Length + 1]; + for (var i = 0; i <= a.Length; i++) + { + d[i, 0] = i; + } + + for (var j = 0; j <= b.Length; j++) + { + d[0, j] = j; + } + + for (var i = 1; i <= a.Length; i++) + { + for (var j = 1; j <= b.Length; j++) + { + var cost = a[i - 1] == b[j - 1] ? 0 : 1; + d[i, j] = Math.Min(Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); + if (i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1]) + { + d[i, j] = Math.Min(d[i, j], d[i - 2, j - 2] + 1); + } + } + } + + return d[a.Length, b.Length]; + } + + /// <summary>The nearest of <paramref name="known"/> to <paramref name="written"/>, when it is near enough.</summary> + public static string? Nearest(string written, IEnumerable<string> known) + { + var best = known.Select(k => (Word: k, Distance: Distance(written, k))) + .OrderBy(entry => entry.Distance).ThenBy(entry => entry.Word, StringComparer.Ordinal).FirstOrDefault(); + var limit = Math.Max(1, written.Length / 3); + return best.Word is not null && best.Distance <= limit ? best.Word : null; + } +} diff --git a/src/Progmasoft.Tazel/Driver/Actions.cs b/src/Progmasoft.Tazel/Driver/Actions.cs new file mode 100644 index 0000000..ad55a7d --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/Actions.cs @@ -0,0 +1,282 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; + +namespace Progmasoft.Tazel.Driver; + +/// <summary> +/// One action of a build: a command line with its environment, the files it reads and the files it writes, all relative +/// to the directory it runs in. Inputs the command finds by itself, such as headers, come from its depfile. +/// </summary> +internal sealed class BuildAction +{ + public required string Description { get; init; } + + public required IReadOnlyList<string> Command { get; init; } + + public required string Directory { get; init; } + + public required IReadOnlyList<string> Inputs { get; init; } + + public required IReadOnlyList<string> Outputs { get; init; } + + public IReadOnlyDictionary<string, string> Environment { get; init; } = new Dictionary<string, string>(); + + /// <summary>The Make-style dependency file the command writes, if it writes one.</summary> + public string? Depfile { get; init; } + + /// <summary>What to say when the command succeeded but did not write one of its outputs.</summary> + public IReadOnlyDictionary<string, string> MissingOutputHints { get; init; } = new Dictionary<string, string>(); + + /// <summary>Work done in Tazel after the command succeeded, such as the links of a shared library.</summary> + public Action? After { get; init; } + + /// <summary>The actions whose outputs this one reads.</summary> + public List<BuildAction> Prerequisites { get; } = []; + + /// <summary>The digest of what the action is apart from its files: command, directory and environment.</summary> + public string Key + { + get + { + var text = new StringBuilder(); + foreach (var part in Command) + { + text.Append(part).Append('\0'); + } + + text.Append('\u0001').Append(Directory).Append('\u0001'); + foreach (var (name, value) in Environment.OrderBy(entry => entry.Key, StringComparer.Ordinal)) + { + text.Append(name).Append('=').Append(value).Append('\0'); + } + + return Digests.Sha256(Encoding.UTF8.GetBytes(text.ToString())); + } + } + + public string Full(string path) => Path.GetFullPath(Path.Combine(Directory, path)); +} + +/// <summary> +/// The SHA-256 of files, kept while a file keeps its size and modification time, so a build reads a file once and a +/// file that is touched but not changed costs one more read. +/// </summary> +internal sealed class Digests +{ + private readonly ConcurrentDictionary<string, (long Size, DateTime Modified, string Digest)> _known = new(StringComparer.Ordinal); + + /// <summary>The SHA-256 of <paramref name="bytes"/> as lower-case hexadecimal.</summary> + public static string Sha256(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes)); + + /// <summary>The digest of <paramref name="file"/>, or null when it is not a readable regular file.</summary> + public string? Of(string file) + { + var info = new FileInfo(file); + if (!info.Exists) + { + return null; + } + + var (size, modified) = (info.Length, info.LastWriteTimeUtc); + if (_known.TryGetValue(file, out var seen) && seen.Size == size && seen.Modified == modified) + { + return seen.Digest; + } + + string digest; + try + { + using var stream = File.OpenRead(file); + digest = Convert.ToHexStringLower(SHA256.HashData(stream)); + } + catch (IOException) + { + return null; + } + catch (UnauthorizedAccessException) + { + return null; + } + + _known[file] = (size, modified, digest); + return digest; + } + + /// <summary>Forgets <paramref name="file"/>, after an action wrote it.</summary> + public void Forget(string file) => _known.TryRemove(file, out _); +} + +/// <summary> +/// Action-level incremental builds. Each action keeps a record beside its first output: its key, and the digest of +/// every input it read and every output it wrote. An action is current while its key is the same, every input has the +/// digest it had, and every output is still what it wrote. Inputs are compared by content, so touching a file reruns +/// nothing, and an output rebuilt to the same bytes reruns none of the actions that read it. +/// </summary> +internal sealed class ActionCache(Digests digests, bool enabled = true) +{ + /// <summary>Whether <paramref name="action"/> would write what it wrote last time; never, when the cache is off.</summary> + public bool IsCurrent(BuildAction action) + { + if (!enabled) + { + return false; + } + + var record = Read(RecordOf(action)); + if (record is null || record.Value.Key != action.Key) + { + return false; + } + + var files = record.Value.Files; + return files.All(entry => digests.Of(entry.Key) == entry.Value) && + action.Outputs.All(output => files.ContainsKey(action.Full(output))) && + action.Inputs.All(input => files.ContainsKey(action.Full(input))); + } + + /// <summary>Records <paramref name="action"/> after it succeeded.</summary> + public void Record(BuildAction action) + { + var files = new SortedDictionary<string, string>(StringComparer.Ordinal); + foreach (var output in action.Outputs) + { + digests.Forget(action.Full(output)); + } + + var discovered = action.Depfile is { } depfile && File.Exists(action.Full(depfile)) + ? Depfiles.Inputs(File.ReadAllText(action.Full(depfile))) + : []; + foreach (var file in action.Inputs.Concat(discovered).Concat(action.Outputs).Select(action.Full)) + { + files[file] = digests.Of(file) ?? throw new IOException($"{file} was not written or cannot be read"); + } + + var text = new StringBuilder().Append("key ").Append(action.Key).Append('\n'); + foreach (var (file, digest) in files) + { + text.Append("file ").Append(digest).Append(' ').Append(file).Append('\n'); + } + + File.WriteAllText(RecordOf(action), text.ToString()); + } + + /// <summary>Forgets <paramref name="action"/>, so that a failed or stopped run is redone.</summary> + public void Forget(BuildAction action) => File.Delete(RecordOf(action)); + + private static string RecordOf(BuildAction action) => action.Full(action.Outputs[0]) + ".action"; + + private static (string Key, Dictionary<string, string> Files)? Read(string file) + { + string[] lines; + try + { + lines = File.ReadAllLines(file); + } + catch (IOException) + { + return null; + } + catch (UnauthorizedAccessException) + { + return null; + } + + if (lines.Length == 0 || !lines[0].StartsWith("key ", StringComparison.Ordinal)) + { + return null; + } + + var files = new Dictionary<string, string>(StringComparer.Ordinal); + foreach (var line in lines.Skip(1)) + { + if (!line.StartsWith("file ", StringComparison.Ordinal) || line.Length < 5 + 64 + 2) + { + return null; + } + + files[line[(5 + 64 + 1)..]] = line[5..(5 + 64)]; + } + + return (lines[0][4..], files); + } +} + +/// <summary>Make-style dependency files, as compilers write them with <c>-MD -MF</c>.</summary> +internal static class Depfiles +{ + /// <summary> + /// The inputs a depfile names: the target, a colon, then the inputs, with <c>\ </c> for a space and a backslash at + /// the end of a line to go on. + /// </summary> + public static IReadOnlyList<string> Inputs(string text) + { + ArgumentNullException.ThrowIfNull(text); + var colon = text.IndexOf(": ", StringComparison.Ordinal); + if (colon < 0) + { + colon = text.IndexOf(":\n", StringComparison.Ordinal); + } + + if (colon < 0) + { + return []; + } + + var body = text[(colon + 1)..]; + var inputs = new List<string>(); + var current = new StringBuilder(); + for (var index = 0; index < body.Length; index++) + { + var c = body[index]; + if (c == '\\' && index + 1 < body.Length && body[index + 1] == ' ') + { + current.Append(' '); + index++; + } + else if (c == '\\' && index + 1 < body.Length && body[index + 1] == '\n') + { + Flush(); + index++; + } + else if (c == '\\' && index + 2 < body.Length && body[index + 1] == '\r' && body[index + 2] == '\n') + { + Flush(); + index += 2; + } + else if (c == '$' && index + 1 < body.Length && body[index + 1] == '$') + { + current.Append('$'); + index++; + } + else if (char.IsWhiteSpace(c)) + { + Flush(); + } + else + { + current.Append(c); + } + } + + Flush(); + return inputs; + + void Flush() + { + if (current.Length > 0) + { + inputs.Add(current.ToString()); + } + + current.Clear(); + } + } +} diff --git a/src/Progmasoft.Tazel/Driver/BuildOptions.cs b/src/Progmasoft.Tazel/Driver/BuildOptions.cs new file mode 100644 index 0000000..c7c9732 --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/BuildOptions.cs @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Driver; + +/// <summary>How a command builds, from its command line and the module.</summary> +internal sealed record BuildOptions +{ + public BuildMode Mode { get; init; } = BuildMode.Debug; + + public Platform Platform { get; init; } = Host.Platform; + + public int Jobs { get; init; } = Environment.ProcessorCount; + + public bool KeepGoing { get; init; } + + public IReadOnlyList<string> FeaturesOn { get; init; } = []; + + public IReadOnlyList<string> FeaturesOff { get; init; } = []; + + public IReadOnlyList<string> CompilerOptions { get; init; } = []; + + public IReadOnlyList<string> CCompilerOptions { get; init; } = []; + + public IReadOnlyList<string> CppCompilerOptions { get; init; } = []; + + public IReadOnlyList<string> LinkerOptions { get; init; } = []; + + public IReadOnlyList<string> ZigCompilerOptions { get; init; } = []; +} + +/// <summary>Where a build writes, below the state directory of the main module.</summary> +internal sealed class OutputLayout(string mainRoot, BuildOptions options) +{ + /// <summary>The root of the main module, where every action runs.</summary> + public string MainRoot { get; } = mainRoot; + + /// <summary>The outputs of this platform and mode, relative to <see cref="MainRoot"/>.</summary> + public string OutRoot { get; } = + $"{ModuleFiles.StateDirectory}/out/{options.Platform.Name()}-{options.Mode.ToString().ToLowerInvariant()}"; + + /// <summary>Where the tests write their logs, relative to <see cref="MainRoot"/>.</summary> + public string TestLogs { get; } = $"{ModuleFiles.StateDirectory}/testlogs"; + + /// <summary>zig's own cache, relative to <see cref="MainRoot"/>.</summary> + public string ZigCache { get; } = $"{ModuleFiles.StateDirectory}/zig-cache"; + + /// <summary>The output directory of the package of <paramref name="target"/>, relative to <see cref="MainRoot"/>.</summary> + public string PackageOut(ProjectTarget target) + { + ArgumentNullException.ThrowIfNull(target); + var package = target.Label.Package; + var prefix = package.Repository is null ? OutRoot : $"{OutRoot}/external/{package.Repository}"; + return package.Path.Length == 0 ? prefix : $"{prefix}/{package.Path}"; + } + + /// <summary>The full path of <paramref name="relative"/>.</summary> + public string Full(string relative) => Path.GetFullPath(Path.Combine(MainRoot, relative)); +} diff --git a/src/Progmasoft.Tazel/Driver/CCPlanner.cs b/src/Progmasoft.Tazel/Driver/CCPlanner.cs new file mode 100644 index 0000000..c5226e0 --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/CCPlanner.cs @@ -0,0 +1,384 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Build.Toolchain.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Driver; + +/// <summary>The languages of the files of a C-family target, from their extensions.</summary> +internal enum SourceLanguage +{ + C, + Cpp, + ObjectiveC, + ObjectiveCpp, + Assembly, + Header, +} + +/// <summary>The C, C++, Objective-C and Objective-C++ part of <see cref="Planner"/>.</summary> +internal sealed partial class Planner +{ + /// <summary>The language of <paramref name="file"/>, or null when no C-family target compiles it.</summary> + public static SourceLanguage? LanguageOf(string file) => Path.GetExtension(file) switch + { + ".c" => SourceLanguage.C, + ".cc" or ".cpp" or ".cxx" or ".c++" => SourceLanguage.Cpp, + ".m" => SourceLanguage.ObjectiveC, + ".mm" => SourceLanguage.ObjectiveCpp, + ".s" or ".S" => SourceLanguage.Assembly, + ".h" or ".hh" or ".hpp" or ".hxx" or ".h++" or ".inc" or ".inl" or ".ipp" or ".tpp" => SourceLanguage.Header, + _ => null, + }; + + private TargetProducts PlanCC(ProjectTarget target) + { + var settings = (CCSettings)target.Settings; + var toolchain = Toolchains.CC(target.Family); + var products = new TargetProducts(); + var moduleRoot = FileSets.ToRoot(target.Module.Root, Layout.MainRoot); + var sources = FileSets.Resolve(settings.Sources, target.PackageDirectory, Layout.MainRoot, target.Place); + var headers = FileSets.Resolve(settings.Headers, target.PackageDirectory, Layout.MainRoot, target.Place) + .Concat(FileSets.Resolve(settings.TextualHeaders, target.PackageDirectory, Layout.MainRoot, target.Place)) + .ToList(); + var ownIncludes = settings.IncludeDirectories + .Select(directory => FileSets.PathIn(directory, target.PackageDirectory, Layout.MainRoot, target.Place, mustExist: true)) + .ToList(); + + // Dependents see this target's headers below the root of its module, and below its include directories. + products.PublicIncludes.Add(moduleRoot); + products.PublicIncludes.AddRange(ownIncludes); + products.PublicDefines.AddRange(settings.PreprocessorDefinitions); + products.PublicHeaders.AddRange(headers); + var includes = new List<string>(products.PublicIncludes); + var defines = new List<string>(settings.PreprocessorDefinitions); + var headerInputs = new List<string>(headers); + var headerActions = new List<BuildAction>(); + foreach (var dependency in Closure(target)) + { + var planned = Plan(dependency); + Add(products.PublicIncludes, planned.PublicIncludes); + Add(products.PublicDefines, planned.PublicDefines); + Add(products.PublicHeaders, planned.PublicHeaders); + products.HeaderActions.AddRange(planned.HeaderActions); + } + + Add(includes, products.PublicIncludes); + Add(defines, products.PublicDefines); + Add(headerInputs, products.PublicHeaders); + headerActions.AddRange(products.HeaderActions); + defines.AddRange(settings.LocalPreprocessorDefinitions); + if (settings is CCExecutableSettings { StampBuildInformation: true }) + { + defines.Add($"TAZEL_BUILD_LABEL=\"{target.Label}\""); + defines.Add($"TAZEL_BUILD_VERSION=\"{target.Module.Info.Version}\""); + } + + var features = EnabledFeatures(target, toolchain, settings.Features); + var directory = Layout.PackageOut(target); + var objectsDirectory = $"{directory}/_objs/{target.Label.Name}"; + var packageRoot = FileSets.ToRoot(target.PackageDirectory, Layout.MainRoot); + var pic = target.Kind != TargetKind.Executable && target.Kind != TargetKind.Test && + Options.Platform.GetOs() != Os.Windows; + var objc = settings as IObjectiveCSettings; + var nonArc = objc is null + ? new HashSet<string>(StringComparer.Ordinal) + : FileSets.Resolve(objc.NonAutomaticReferenceCountingSources, target.PackageDirectory, Layout.MainRoot, target.Place) + .ToHashSet(StringComparer.Ordinal); + var objects = new List<string>(); + var compiles = new List<BuildAction>(); + foreach (var source in sources.Concat(nonArc.Where(file => !sources.Contains(file)))) + { + var language = LanguageOf(source) ?? throw new ProjectException( + $"{target.Place}: {target.Label} cannot compile '{source}'; its extension is not C, C++, Objective-C or assembly"); + if (language == SourceLanguage.Header) + { + headerInputs.Add(source); + continue; + } + + if (language is SourceLanguage.ObjectiveC or SourceLanguage.ObjectiveCpp && target.Family != Family.ObjectiveC) + { + throw new ProjectException($"{target.Place}: '{source}' is Objective-C; declare {target.Label} with ObjectiveC"); + } + + var relative = source.StartsWith(packageRoot + "/", StringComparison.Ordinal) ? source[(packageRoot.Length + 1)..] : source; + var objectFile = $"{objectsDirectory}/{relative}.o"; + var cxx = language is SourceLanguage.Cpp or SourceLanguage.ObjectiveCpp; + var action = language switch + { + SourceLanguage.C => CCAction.CCompile, + SourceLanguage.Cpp => CCAction.CppCompile, + SourceLanguage.ObjectiveC => CCAction.ObjectiveCCompile, + SourceLanguage.ObjectiveCpp => CCAction.ObjectiveCppCompile, + _ => CCAction.Assemble, + }; + var command = new List<string>((cxx ? toolchain.Cpp : toolchain.C).Command); + command.AddRange(ModeFlags()); + command.AddRange(Flags(features, action)); + if (pic) + { + command.Add("-fPIC"); + } + + command.AddRange(includes.Select(include => "-I" + include)); + command.AddRange(defines.Select(define => "-D" + define)); + command.AddRange(settings.CompilerOptions); + command.AddRange(cxx ? settings.CppCompilerOptions : settings.CCompilerOptions); + if (objc is not null && language is SourceLanguage.ObjectiveC or SourceLanguage.ObjectiveCpp) + { + command.Add(nonArc.Contains(source) ? "-fno-objc-arc" : "-fobjc-arc"); + } + + if (objc is { EnableClangModules: true }) + { + command.Add("-fmodules"); + if (objc.ModuleName is { } moduleName) + { + command.Add($"-fmodule-name={moduleName}"); + } + + if (objc.ModuleMap is { } map) + { + command.Add("-fmodule-map-file=" + + FileSets.PathIn(map, target.PackageDirectory, Layout.MainRoot, target.Place, mustExist: true)); + } + } + + command.AddRange(Options.CompilerOptions); + command.AddRange(cxx ? Options.CppCompilerOptions : Options.CCompilerOptions); + command.AddRange(["-MD", "-MF", objectFile + ".d", "-c", source, "-o", objectFile]); + var compile = new BuildAction + { + Description = $"Compiling {target.Label} {relative}", + Command = command, + Directory = Layout.MainRoot, + Inputs = headerInputs.Prepend(source).Distinct(StringComparer.Ordinal).ToList(), + Outputs = [objectFile], + Environment = ActionEnvironment, + Depfile = objectFile + ".d", + }; + compile.Prerequisites.AddRange(headerActions); + compiles.Add(compile); + objects.Add(objectFile); + } + + products.LinkTail.AddRange(settings.LinkerOptions); + products.LinkTail.AddRange(settings.SdkFrameworks.SelectMany(framework => new[] { "-framework", framework })); + products.LinkTail.AddRange(settings.WeakSdkFrameworks.SelectMany(framework => new[] { "-weak_framework", framework })); + products.LinkTail.AddRange(settings.SdkDynamicLibraries.Select(library => "-l" + library)); + switch (target.Kind) + { + case TargetKind.StaticLibrary: + PlanArchive(target, toolchain, features, products, directory, objects, compiles); + break; + case TargetKind.SharedLibrary: + PlanLink(target, toolchain, features, products, directory, objects, compiles, shared: true); + break; + default: + PlanLink(target, toolchain, features, products, directory, objects, compiles, shared: false); + break; + } + + return products; + } + + private void PlanArchive( + ProjectTarget target, CCToolchain toolchain, IReadOnlyList<Feature> features, TargetProducts products, + string directory, List<string> objects, List<BuildAction> compiles) + { + var settings = (CCStaticLibrarySettings)target.Settings; + var library = $"{directory}/{StaticLibraryName(target.Label.Name)}"; + var command = new List<string>(toolchain.Archiver.Command); + if (toolchain.ArchiverIsLibtool) + { + command.AddRange(Flags(features, CCAction.CppLinkStaticLibrary)); + command.AddRange(["-static", "-o", library]); + } + else + { + // Apple's ar has no D; ZERO_AR_DATE in the environment of the actions makes it deterministic instead. + var appleAr = Host.Platform.GetOs() == Os.MacOS && + Path.GetFileNameWithoutExtension(toolchain.Archiver.Program) == "ar"; + command.Add(appleAr ? "rcs" : "rcsD"); + command.AddRange(Flags(features, CCAction.CppLinkStaticLibrary)); + command.Add(library); + } + + command.AddRange(objects); + var archive = new BuildAction + { + Description = $"Archiving {target.Label}", + Command = command, + Directory = Layout.MainRoot, + Inputs = objects, + Outputs = [library], + Environment = ActionEnvironment, + }; + archive.Prerequisites.AddRange(compiles); + products.Main = archive; + products.Library = library; + products.AlwaysLink = settings.AlwaysLink; + } + + private void PlanLink( + ProjectTarget target, CCToolchain toolchain, IReadOnlyList<Feature> features, TargetProducts products, + string directory, List<string> objects, List<BuildAction> compiles, bool shared) + { + var settings = (CCSettings)target.Settings; + var command = new List<string>(toolchain.Linker.Command); + command.AddRange(ModeFlags()); + command.AddRange(Flags(features, shared ? CCAction.CppLinkSharedLibrary : CCAction.CppLinkExecutable)); + string output; + Action? after = null; + if (shared) + { + var version = ((CCSharedLibrarySettings)settings).LibraryVersion; + var (file, linkWith, soname) = SharedLibraryNames(directory, target.Label.Name, version); + output = file; + var os = Options.Platform.GetOs(); + command.Add(os == Os.MacOS ? "-dynamiclib" : "-shared"); + if (os == Os.MacOS) + { + command.AddRange(["-install_name", $"@rpath/{soname}"]); + if (version is not null) + { + command.AddRange(["-current_version", version.ToString(Math.Min(3, FieldCount(version))), + "-compatibility_version", $"{version.Major}.0.0"]); + } + } + else if (os != Os.Windows && soname is not null) + { + command.Add($"-Wl,-soname,{soname}"); + } + + products.Library = linkWith; + products.IsShared = true; + after = SonameLinks(file, soname, target.Label.Name); + } + else + { + output = $"{directory}/{ExecutableName(target.Label.Name)}"; + products.Executable = output; + if (settings is CCExecutableSettings { LinkingMode: LinkingMode.FullyStatic }) + { + command.Add("-static"); + } + } + + command.AddRange(["-o", output]); + command.AddRange(objects); + var (arguments, inputs, actions, directories) = LinkLibraries(target, directory); + command.AddRange(arguments); + command.AddRange(settings.LinkerOptions); + command.AddRange(settings.SdkFrameworks.SelectMany(framework => new[] { "-framework", framework })); + command.AddRange(settings.WeakSdkFrameworks.SelectMany(framework => new[] { "-weak_framework", framework })); + command.AddRange(settings.SdkDynamicLibraries.Select(library => "-l" + library)); + var extra = settings switch + { + CCSharedLibrarySettings library => library.AdditionalLinkerInputs, + CCExecutableSettings program => program.AdditionalLinkerInputs, + _ => Files.None, + }; + var extraFiles = FileSets.Resolve(extra, target.PackageDirectory, Layout.MainRoot, target.Place); + command.AddRange(Options.LinkerOptions); + var link = new BuildAction + { + Description = $"Linking {target.Label}", + Command = command, + Directory = Layout.MainRoot, + Inputs = objects.Concat(inputs).Concat(extraFiles).Distinct(StringComparer.Ordinal).ToList(), + Outputs = shared && products.Library != output ? [output, products.Library!] : [output], + Environment = ActionEnvironment, + After = after, + }; + link.Prerequisites.AddRange(compiles); + link.Prerequisites.AddRange(actions); + products.Main = link; + products.SharedLibraryDirectories.AddRange(directories); + if (shared) + { + // What links this library still needs the shared libraries it loads. + products.LinkTail.Clear(); + } + } + + /// <summary>The features of <paramref name="toolchain"/> that are on for <paramref name="target"/>.</summary> + private List<Feature> EnabledFeatures(ProjectTarget target, CCToolchain toolchain, IReadOnlyList<FeatureToggle> toggles) + { + var on = toolchain.Features.Where(feature => feature.Settings.Enabled).Select(feature => feature.Name) + .ToHashSet(StringComparer.Ordinal); + on.UnionWith(Options.FeaturesOn); + on.ExceptWith(Options.FeaturesOff); + foreach (var toggle in toggles) + { + if (toolchain.Features.All(feature => feature.Name != toggle.Name)) + { + throw new ProjectException( + $"{target.Place}: the toolchain {toolchain.Name} has no feature '{toggle.Name}'"); + } + + if (toggle.Enabled) + { + on.Add(toggle.Name); + } + else + { + on.Remove(toggle.Name); + } + } + + return toolchain.Features.Where(feature => on.Contains(feature.Name)).ToList(); + } + + private static IEnumerable<string> Flags(IReadOnlyList<Feature> features, CCAction action) => + features.SelectMany(feature => feature.Settings.FlagSets) + .Where(set => set.Actions.Contains(action)) + .SelectMany(set => set.Flags); + + private IEnumerable<string> ModeFlags() => + Options.Mode == BuildMode.Debug ? ["-g"] : ["-O2", "-DNDEBUG"]; + + /// <summary>Every target <paramref name="target"/> depends on, near or far, each once.</summary> + private static List<ProjectTarget> Closure(ProjectTarget target) + { + var seen = new HashSet<ProjectTarget>(); + var order = new List<ProjectTarget>(); + var stack = new Stack<ProjectTarget>(target.Dependencies.AsEnumerable().Reverse()); + while (stack.Count > 0) + { + var next = stack.Pop(); + if (!seen.Add(next)) + { + continue; + } + + order.Add(next); + foreach (var deeper in next.Dependencies.AsEnumerable().Reverse()) + { + stack.Push(deeper); + } + } + + return order; + } + + private static void Add(List<string> into, IEnumerable<string> items) + { + foreach (var item in items) + { + if (!into.Contains(item)) + { + into.Add(item); + } + } + } +} diff --git a/src/Progmasoft.Tazel/Driver/Executor.cs b/src/Progmasoft.Tazel/Driver/Executor.cs new file mode 100644 index 0000000..0352461 --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/Executor.cs @@ -0,0 +1,130 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Output; + +namespace Progmasoft.Tazel.Driver; + +/// <summary> +/// Runs the actions of a build, at most <c>jobs</c> at a time, each once all it reads has been made. After a failure no +/// action starts unless <c>keepGoing</c> asks for it; those running are let finish, so no compiler is left writing +/// behind the back of the command. +/// </summary> +internal sealed class Executor(int jobs, bool keepGoing, ActionCache cache, Reporter reporter) +{ + private readonly System.Collections.Concurrent.ConcurrentDictionary<BuildAction, bool> _made = new(); + private int _done; + private int _failed; + + /// <summary>Whether <paramref name="action"/> was made, now or by an earlier build.</summary> + public bool Succeeded(BuildAction action) => _made.ContainsKey(action); + + /// <summary>How many actions failed.</summary> + public int Failed => _failed; + + /// <summary>Runs <paramref name="goals"/> and what they need; true when all of them were made.</summary> + public async Task<bool> RunAsync(IReadOnlyCollection<BuildAction> goals, CancellationToken cancel) + { + var all = Closure(goals); + var total = all.Count; + using var stop = CancellationTokenSource.CreateLinkedTokenSource(cancel); + using var slots = new SemaphoreSlim(Math.Max(1, jobs)); + var tasks = new Dictionary<BuildAction, Lazy<Task<bool>>>(); + foreach (var action in all) + { + tasks[action] = new Lazy<Task<bool>>(() => RunOneAsync(action), LazyThreadSafetyMode.ExecutionAndPublication); + } + + var results = await Task.WhenAll(goals.Select(goal => tasks[goal].Value)).ConfigureAwait(false); + return results.All(result => result); + + async Task<bool> RunOneAsync(BuildAction action) + { + var ready = await Task.WhenAll(action.Prerequisites.Select(prerequisite => tasks[prerequisite].Value)) + .ConfigureAwait(false); + if (!ready.All(result => result) || stop.IsCancellationRequested) + { + return false; + } + + await slots.WaitAsync(CancellationToken.None).ConfigureAwait(false); + try + { + if (stop.IsCancellationRequested) + { + return false; + } + + if (cache.IsCurrent(action)) + { + action.After?.Invoke(); + Interlocked.Increment(ref _done); + _made[action] = true; + return true; + } + + foreach (var output in action.Outputs) + { + var full = action.Full(output); + Directory.CreateDirectory(Path.GetDirectoryName(full)!); + File.Delete(full); + } + + cache.Forget(action); + var result = await Processes.RunAsync(action.Command, action.Directory, action.Environment, null, stop.Token) + .ConfigureAwait(false); + var missing = action.Outputs.FirstOrDefault(output => !File.Exists(action.Full(output))); + if (result.ExitCode != 0 || missing is not null) + { + var hint = missing is not null && action.MissingOutputHints.TryGetValue(missing, out var said) ? $"; {said}" : ""; + var output = result.ExitCode == 0 ? result.Output + $"{missing} was not written{hint}\n" : result.Output; + Interlocked.Increment(ref _failed); + reporter.ActionFailed(action.Description, action.Command, output); + if (!keepGoing) + { + await stop.CancelAsync().ConfigureAwait(false); + } + + return false; + } + + cache.Record(action); + action.After?.Invoke(); + _made[action] = true; + reporter.ActionDone(Interlocked.Increment(ref _done), total, action.Description, result.Output); + return true; + } + finally + { + slots.Release(); + } + } + } + + private static List<BuildAction> Closure(IEnumerable<BuildAction> goals) + { + var seen = new HashSet<BuildAction>(); + var order = new List<BuildAction>(); + var stack = new Stack<BuildAction>(goals); + while (stack.Count > 0) + { + var action = stack.Pop(); + if (seen.Add(action)) + { + order.Add(action); + foreach (var prerequisite in action.Prerequisites) + { + stack.Push(prerequisite); + } + } + } + + return order; + } +} diff --git a/src/Progmasoft.Tazel/Driver/Planner.cs b/src/Progmasoft.Tazel/Driver/Planner.cs new file mode 100644 index 0000000..e5b7d62 --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/Planner.cs @@ -0,0 +1,251 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Driver; + +/// <summary>What a planned target makes, and what its dependents take from it.</summary> +internal sealed class TargetProducts +{ + /// <summary>The action that makes the target's main file: the archive, the link or the zig command.</summary> + public BuildAction? Main { get; set; } + + /// <summary>The file dependents link: a static library, a shared library or its import library.</summary> + public string? Library { get; set; } + + public bool IsShared { get; set; } + + public bool AlwaysLink { get; set; } + + /// <summary>The program, for executables and tests.</summary> + public string? Executable { get; set; } + + /// <summary>The directories of the shared libraries a program loads, for rpath and PATH.</summary> + public List<string> SharedLibraryDirectories { get; } = []; + + /// <summary>Include directories for this target's dependents.</summary> + public List<string> PublicIncludes { get; } = []; + + /// <summary>Macros for this target's dependents.</summary> + public List<string> PublicDefines { get; } = []; + + /// <summary>Headers dependents may include, for the inputs of their compilations.</summary> + public List<string> PublicHeaders { get; } = []; + + /// <summary>Actions whose outputs dependents' compilations read, such as headers zig emits.</summary> + public List<BuildAction> HeaderActions { get; } = []; + + /// <summary>Linker options, frameworks and libraries that go to whatever links this library.</summary> + public List<string> LinkTail { get; } = []; +} + +/// <summary>Turns targets into the actions that build them.</summary> +internal sealed partial class Planner +{ + private readonly Dictionary<ProjectTarget, TargetProducts> _planned = []; + + public Planner(Workspace workspace, BuildOptions options, ToolchainChooser toolchains) + { + Workspace = workspace; + Options = options; + Toolchains = toolchains; + Layout = new OutputLayout(workspace.Main.Root, options); + ActionEnvironment = Processes.ForActions(); + } + + public Workspace Workspace { get; } + + public BuildOptions Options { get; } + + public ToolchainChooser Toolchains { get; } + + public OutputLayout Layout { get; } + + public Dictionary<string, string> ActionEnvironment { get; } + + /// <summary>What <paramref name="target"/> makes, planning it and what it depends on once.</summary> + public TargetProducts Plan(ProjectTarget target) + { + if (_planned.TryGetValue(target, out var known)) + { + return known; + } + + var products = target.Family == Family.Zig ? PlanZig(target) : PlanCC(target); + _planned[target] = products; + return products; + } + + /// <summary>Checks the features the command line names against the toolchains the build used.</summary> + public void CheckCommandLineFeatures(IEnumerable<CCToolchain> used) + { + var known = used.SelectMany(toolchain => toolchain.Features).Select(feature => feature.Name).ToHashSet(StringComparer.Ordinal); + foreach (var name in Options.FeaturesOn.Concat(Options.FeaturesOff)) + { + if (!known.Contains(name)) + { + var near = Cli.Suggestions.Nearest(name, known); + throw new ProjectException( + $"no toolchain of this build has the feature '{name}'{(near is null ? "" : $"; did you mean '{near}'?")}"); + } + } + } + + /// <summary>The libraries a link takes for <paramref name="target"/>'s dependencies, each before what it needs.</summary> + private List<(ProjectTarget Target, TargetProducts Products)> LinkOrder(ProjectTarget target) + { + var post = new List<(ProjectTarget Target, TargetProducts Products)>(); + var seen = new HashSet<(ProjectTarget, bool)>(); + foreach (var dependency in target.Dependencies) + { + Visit(dependency, belowShared: false); + } + + // Reversed, each library comes before the libraries it needs; a library reached twice keeps its last place. + post.Reverse(); + var placed = new HashSet<ProjectTarget>(); + return post.Where(entry => placed.Add(entry.Target)).ToList(); + + void Visit(ProjectTarget library, bool belowShared) + { + if (!seen.Add((library, belowShared))) + { + return; + } + + var products = Plan(library); + // What a shared library links statically is inside it; only its shared libraries still have to be found. + foreach (var next in library.Dependencies) + { + Visit(next, belowShared || products.IsShared); + } + + if (!belowShared || products.IsShared) + { + post.Add((library, products)); + } + } + } + + /// <summary>The linker arguments for the libraries of <paramref name="target"/>, and the actions that make them.</summary> + private (List<string> Arguments, List<string> Inputs, List<BuildAction> Actions, List<string> SharedDirectories) + LinkLibraries(ProjectTarget target, string outputDirectory, bool forZig = false) + { + var arguments = new List<string>(); + var inputs = new List<string>(); + var actions = new List<BuildAction>(); + var sharedDirectories = new List<string>(); + var tail = new List<string>(); + var os = Options.Platform.GetOs(); + foreach (var (_, products) in LinkOrder(target)) + { + if (products.Main is { } main) + { + actions.Add(main); + } + + if (products.Library is { } library) + { + inputs.Add(library); + if (products.AlwaysLink && !products.IsShared && !forZig) + { + arguments.AddRange(os == Os.MacOS + ? [$"-Wl,-force_load,{library}"] + : ["-Wl,--whole-archive", library, "-Wl,--no-whole-archive"]); + } + else + { + arguments.Add(library); + } + + if (products.IsShared) + { + var directory = Path.GetDirectoryName(library)!.Replace('\\', '/'); + if (!sharedDirectories.Contains(directory)) + { + sharedDirectories.Add(directory); + } + } + } + + tail.AddRange(products.LinkTail); + } + + foreach (var directory in forZig ? [] : sharedDirectories) + { + var relative = Path.GetRelativePath(outputDirectory, directory).Replace('\\', '/'); + var suffix = relative == "." ? "" : "/" + relative; + if (os == Os.MacOS) + { + arguments.Add($"-Wl,-rpath,@loader_path{suffix}"); + } + else if (os != Os.Windows) + { + arguments.Add($"-Wl,-rpath,$ORIGIN{suffix}"); + } + } + + arguments.AddRange(tail); + return (arguments, inputs, actions, sharedDirectories); + } + + private static string Sanitized(string text) => new(text.Select(c => char.IsAsciiLetterOrDigit(c) ? c : '_').ToArray()); + + /// <summary>The file names of libraries and programs on the platform of the build.</summary> + private string StaticLibraryName(string name) => + Options.Platform.GetOs() == Os.Windows ? $"{name}.lib" : $"lib{name}.a"; + + private string ExecutableName(string name) => Options.Platform.GetOs() == Os.Windows ? $"{name}.exe" : name; + + /// <summary>The file a shared library is written to, the file its dependents link, and its soname.</summary> + private (string File, string LinkWith, string? Soname) SharedLibraryNames(string directory, string name, Version? version) + { + switch (Options.Platform.GetOs()) + { + case Os.Windows: + return ($"{directory}/{name}.dll", $"{directory}/{name}.lib", null); + case Os.MacOS: + var mac = version is null ? $"lib{name}.dylib" : $"lib{name}.{version.Major}.dylib"; + return ($"{directory}/{mac}", $"{directory}/{mac}", mac); + default: + if (version is null) + { + return ($"{directory}/lib{name}.so", $"{directory}/lib{name}.so", $"lib{name}.so"); + } + + var full = $"lib{name}.so.{version.ToString(Math.Min(3, FieldCount(version)))}"; + return ($"{directory}/{full}", $"{directory}/{full}", $"lib{name}.so.{version.Major}"); + } + } + + private static int FieldCount(Version version) => version.Build >= 0 ? 3 : version.Minor >= 0 ? 2 : 1; + + /// <summary>Makes <c>libx.so.1</c> and <c>libx.so</c> point at <c>libx.so.1.2.0</c>.</summary> + private Action? SonameLinks(string file, string? soname, string name) + { + if (Options.Platform.GetOs() is Os.Windows or Os.MacOS || soname is null || Path.GetFileName(file) == soname) + { + return null; + } + + var directory = Layout.Full(Path.GetDirectoryName(file)!); + var target = Path.GetFileName(file); + return () => + { + foreach (var link in new[] { soname, $"lib{name}.so" }) + { + var path = Path.Combine(directory, link); + File.Delete(path); + File.CreateSymbolicLink(path, target); + } + }; + } +} diff --git a/src/Progmasoft.Tazel/Driver/Processes.cs b/src/Progmasoft.Tazel/Driver/Processes.cs new file mode 100644 index 0000000..7cdd98c --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/Processes.cs @@ -0,0 +1,177 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Progmasoft.Tazel.Driver; + +/// <summary>What a process did: its exit status, and its output and errors together, in the order they came.</summary> +/// <param name="ExitCode">The exit status; -1 when it could not start or ran out of time.</param> +/// <param name="Output">What it printed.</param> +/// <param name="TimedOut">Whether it was stopped because it ran out of time.</param> +internal sealed record ProcessResult(int ExitCode, string Output, bool TimedOut = false); + +/// <summary>Starts programs directly, with an argument list and no shell between.</summary> +internal static class Processes +{ + /// <summary> + /// Runs <paramref name="command"/> in <paramref name="directory"/> with exactly <paramref name="environment"/>, and + /// keeps what it prints. It is stopped, with what it started, after <paramref name="timeout"/>. + /// </summary> + public static async Task<ProcessResult> RunAsync( + IReadOnlyList<string> command, + string directory, + IReadOnlyDictionary<string, string> environment, + TimeSpan? timeout, + CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(command); + ArgumentNullException.ThrowIfNull(environment); + var start = new ProcessStartInfo(command[0]) + { + WorkingDirectory = directory, + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = true, + UseShellExecute = false, + CreateNoWindow = true, + StandardOutputEncoding = Encoding.UTF8, + StandardErrorEncoding = Encoding.UTF8, + }; + for (var i = 1; i < command.Count; i++) + { + start.ArgumentList.Add(command[i]); + } + + start.Environment.Clear(); + foreach (var (name, value) in environment) + { + start.Environment[name] = value; + } + + var output = new StringBuilder(); + using var process = new Process { StartInfo = start }; + process.OutputDataReceived += (_, line) => Append(output, line.Data); + process.ErrorDataReceived += (_, line) => Append(output, line.Data); + try + { + process.Start(); + } + catch (Win32Exception error) + { + return new ProcessResult(-1, $"{command[0]} could not be started: {error.Message}"); + } + + process.StandardInput.Close(); + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + using var limit = CancellationTokenSource.CreateLinkedTokenSource(cancel); + if (timeout is { } span) + { + limit.CancelAfter(span); + } + + try + { + await process.WaitForExitAsync(limit.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + process.Kill(entireProcessTree: true); + await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false); + var timedOut = !cancel.IsCancellationRequested; + return new ProcessResult(-1, Text(output), TimedOut: timedOut); + } + + // WaitForExitAsync returns once the output has been read to its end as well. + return new ProcessResult(process.ExitCode, Text(output)); + } + + /// <summary>Runs <paramref name="command"/> with the terminal of Tazel, as <c>tazel run</c> does.</summary> + public static int RunAttached(IReadOnlyList<string> command, string directory, IReadOnlyDictionary<string, string> environment) + { + ArgumentNullException.ThrowIfNull(command); + ArgumentNullException.ThrowIfNull(environment); + var start = new ProcessStartInfo(command[0]) { WorkingDirectory = directory, UseShellExecute = false }; + for (var i = 1; i < command.Count; i++) + { + start.ArgumentList.Add(command[i]); + } + + start.Environment.Clear(); + foreach (var (name, value) in environment) + { + start.Environment[name] = value; + } + + using var process = Process.Start(start) ?? throw new InvalidOperationException($"{command[0]} did not start"); + process.WaitForExit(); + return process.ExitCode; + } + + /// <summary>Tazel's own environment, for what runs as the user would run it.</summary> + public static Dictionary<string, string> Inherited() + { + var environment = new Dictionary<string, string>(StringComparer.Ordinal); + foreach (System.Collections.DictionaryEntry entry in System.Environment.GetEnvironmentVariables()) + { + if (entry.Key is string name && entry.Value is string value) + { + environment[name] = value; + } + } + + return environment; + } + + /// <summary> + /// The small environment the actions of a build run with: the programs on PATH find their own files, and nothing + /// else of the user's environment changes what they make. + /// </summary> + public static Dictionary<string, string> ForActions() + { + var environment = new Dictionary<string, string>(StringComparer.Ordinal) { ["LC_ALL"] = "C" }; + foreach (var name in new[] { "PATH", "TMPDIR", "TMP", "TEMP", "SYSTEMROOT", "SystemRoot", "WINDIR", "HOME", + "DEVELOPER_DIR", "SDKROOT", "INCLUDE", "LIB", "LIBPATH" }) + { + if (System.Environment.GetEnvironmentVariable(name) is { } value) + { + environment[name] = value; + } + } + + if (OperatingSystem.IsMacOS()) + { + environment["ZERO_AR_DATE"] = "1"; + } + + return environment; + } + + private static void Append(StringBuilder output, string? line) + { + if (line is null) + { + return; + } + + lock (output) + { + output.Append(line).Append('\n'); + } + } + + private static string Text(StringBuilder output) + { + lock (output) + { + return output.ToString(); + } + } +} diff --git a/src/Progmasoft.Tazel/Driver/TestRunner.cs b/src/Progmasoft.Tazel/Driver/TestRunner.cs new file mode 100644 index 0000000..85a8321 --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/TestRunner.cs @@ -0,0 +1,204 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Driver; + +/// <summary>The files a program reads, in the directory it runs in, as Bazel's runfiles.</summary> +internal static class Runfiles +{ + /// <summary> + /// Makes the runfiles directory of <paramref name="target"/> beside its program, with each file of RuntimeData at its + /// path in the module, and returns it. + /// </summary> + public static string Prepare(ProjectTarget target, TargetProducts products, OutputLayout layout) + { + var directory = layout.Full(products.Executable! + ".runfiles"); + if (Directory.Exists(directory)) + { + Directory.Delete(directory, recursive: true); + } + + Directory.CreateDirectory(directory); + var data = ((IRunSettings)target.Settings).RuntimeData; + foreach (var file in FileSets.Resolve(data, target.PackageDirectory, target.Module.Root, target.Place)) + { + var destination = Path.Combine(directory, file); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + File.Copy(Path.Combine(target.Module.Root, file), destination); + } + + return directory; + } + + /// <summary>The environment variable that finds shared libraries on Windows, with the directories prepended.</summary> + public static void AddLibraryPath(Dictionary<string, string> environment, TargetProducts products, OutputLayout layout) + { + if (!OperatingSystem.IsWindows() || products.SharedLibraryDirectories.Count == 0) + { + return; + } + + var directories = products.SharedLibraryDirectories.Select(layout.Full); + environment.TryGetValue("PATH", out var path); + environment["PATH"] = string.Join(Path.PathSeparator, directories.Append(path ?? "")); + } +} + +/// <summary>Runs tests: each with a small environment, its own temporary directory, a timeout, and retries when flaky.</summary> +internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporter) +{ + /// <summary>The timeout of a size, as in Bazel.</summary> + public static TimeSpan TimeoutOf(TestSize size) => size switch + { + TestSize.Small => TimeSpan.FromMinutes(1), + TestSize.Medium => TimeSpan.FromMinutes(5), + TestSize.Large => TimeSpan.FromMinutes(15), + _ => TimeSpan.FromMinutes(60), + }; + + /// <summary>Runs each test that was built and reports every one.</summary> + public async Task<IReadOnlyList<TestOutcome>> RunAsync( + IReadOnlyList<(ProjectTarget Target, TargetProducts Products, bool Built)> tests, CancellationToken cancel) + { + using var slots = new SemaphoreSlim(Math.Max(1, jobs)); + var outcomes = await Task.WhenAll(tests.Select(async test => + { + if (!test.Built) + { + return new TestOutcome(test.Target.Label.ToString(), TestStatus.NotBuilt, TimeSpan.Zero, ""); + } + + var exclusive = test.Target.Settings.Tags.Contains("exclusive", StringComparer.Ordinal); + var held = exclusive ? Math.Max(1, jobs) : 1; + for (var i = 0; i < held; i++) + { + await slots.WaitAsync(cancel).ConfigureAwait(false); + } + + try + { + return await RunOneAsync(test.Target, test.Products, cancel).ConfigureAwait(false); + } + finally + { + slots.Release(held); + } + })).ConfigureAwait(false); + foreach (var outcome in outcomes.Where(o => o.Status is TestStatus.Failed or TestStatus.TimedOut)) + { + reporter.TestLog(outcome.Label, outcome.Log); + } + + return outcomes.OrderBy(o => o.Label, StringComparer.Ordinal).ToList(); + } + + private async Task<TestOutcome> RunOneAsync(ProjectTarget target, TargetProducts products, CancellationToken cancel) + { + var settings = (ITestSettings)target.Settings; + var runfiles = Runfiles.Prepare(target, products, layout); + var logDirectory = layout.Full($"{layout.TestLogs}/{Sanitize(target.Label.ToString())}"); + if (Directory.Exists(logDirectory)) + { + Directory.Delete(logDirectory, recursive: true); + } + + Directory.CreateDirectory(logDirectory); + var timeout = settings.Timeout ?? TimeoutOf(settings.TestSize); + var attempts = settings.Flaky ? 3 : 1; + var watch = Stopwatch.StartNew(); + var log = new StringBuilder(); + for (var attempt = 1; attempt <= attempts; attempt++) + { + var failed = false; + var timedOut = false; + for (var shard = 0; shard < settings.ShardCount; shard++) + { + var environment = Environment(target, settings, logDirectory, shard, runfiles); + Runfiles.AddLibraryPath(environment, products, layout); + var command = new List<string> { layout.Full(products.Executable!) }; + command.AddRange(settings.Arguments); + var result = await Processes.RunAsync(command, runfiles, environment, timeout, cancel).ConfigureAwait(false); + if (settings.ShardCount > 1) + { + log.Append(CultureInfo.InvariantCulture, $"--- shard {shard + 1} of {settings.ShardCount} ---\n"); + } + + log.Append(result.Output); + if (result.TimedOut) + { + log.Append(CultureInfo.InvariantCulture, $"the test ran out of its {timeout.TotalSeconds:0} s\n"); + timedOut = true; + } + + failed |= result.ExitCode != 0; + } + + await File.WriteAllTextAsync(Path.Combine(logDirectory, "test.log"), log.ToString(), cancel).ConfigureAwait(false); + if (!failed) + { + var status = attempt == 1 ? TestStatus.Passed : TestStatus.Flaky; + return new TestOutcome(target.Label.ToString(), status, watch.Elapsed, log.ToString()); + } + + if (attempt == attempts) + { + return new TestOutcome(target.Label.ToString(), timedOut ? TestStatus.TimedOut : TestStatus.Failed, + watch.Elapsed, log.ToString()); + } + + log.Append(CultureInfo.InvariantCulture, $"--- attempt {attempt} failed; the test is flaky, so it runs again ---\n"); + } + + throw new InvalidOperationException("a test ended without an outcome"); + } + + private static Dictionary<string, string> Environment( + ProjectTarget target, ITestSettings settings, string logDirectory, int shard, string runfiles) + { + var environment = new Dictionary<string, string>(StringComparer.Ordinal); + foreach (var name in settings.InheritedEnvironmentVariables.Concat(["PATH", "SYSTEMROOT", "SystemRoot"])) + { + if (System.Environment.GetEnvironmentVariable(name) is { } value) + { + environment[name] = value; + } + } + + var temporary = Path.Combine(logDirectory, $"tmp{shard}"); + Directory.CreateDirectory(temporary); + environment["TEST_TMPDIR"] = temporary; + environment["TMPDIR"] = temporary; + environment["HOME"] = temporary; + environment["TEST_SRCDIR"] = runfiles; + environment["TEST_TARGET"] = target.Label.ToString(); + if (settings.ShardCount > 1) + { + environment["TEST_TOTAL_SHARDS"] = settings.ShardCount.ToString(CultureInfo.InvariantCulture); + environment["TEST_SHARD_INDEX"] = shard.ToString(CultureInfo.InvariantCulture); + } + + foreach (var (name, value) in settings.EnvironmentVariables) + { + environment[name] = value; + } + + return environment; + } + + private static string Sanitize(string label) => + label.TrimStart('/', '@').Replace(':', '/').Replace("//", "/", StringComparison.Ordinal); +} diff --git a/src/Progmasoft.Tazel/Driver/Toolchains.cs b/src/Progmasoft.Tazel/Driver/Toolchains.cs new file mode 100644 index 0000000..0f0ab4b --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/Toolchains.cs @@ -0,0 +1,262 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Dsl.Build.Toolchain.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Driver; + +/// <summary>A program and the arguments that always come first, such as <c>zig cc</c>.</summary> +/// <param name="Program">The program, a full path.</param> +/// <param name="Prefix">The arguments before any other.</param> +internal sealed record Tool(string Program, IReadOnlyList<string> Prefix) +{ + public IEnumerable<string> Command => Prefix.Prepend(Program); + + public override string ToString() => string.Join(' ', Command); +} + +/// <summary>The machine Tazel runs on, and programs on its PATH.</summary> +internal static class Host +{ + /// <summary>The platform of this machine.</summary> + public static Platform Platform { get; } = Detect(); + + public static bool IsWindows => OperatingSystem.IsWindows(); + + /// <summary>The full path of <paramref name="name"/>: as written when it has a directory, else from PATH.</summary> + public static string? Which(string name) + { + ArgumentNullException.ThrowIfNull(name); + if (name.Contains('/', StringComparison.Ordinal) || name.Contains('\\', StringComparison.Ordinal)) + { + return File.Exists(name) ? Path.GetFullPath(name) : null; + } + + var extensions = IsWindows + ? (Environment.GetEnvironmentVariable("PATHEXT") ?? ".EXE;.CMD;.BAT").Split(';', StringSplitOptions.RemoveEmptyEntries) + : [""]; + foreach (var directory in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)) + { + if (directory.Length == 0) + { + continue; + } + + foreach (var extension in extensions.Prepend("")) + { + var candidate = Path.Combine(directory, name + extension); + if (File.Exists(candidate) && (IsWindows || IsExecutable(candidate))) + { + return candidate; + } + } + } + + return null; + } + + private static bool IsExecutable(string file) => + !OperatingSystem.IsWindows() && (File.GetUnixFileMode(file) & UnixFileMode.UserExecute) != 0; + + private static Platform Detect() + { + var arm = RuntimeInformation.OSArchitecture == Architecture.Arm64; + if (OperatingSystem.IsWindows()) + { + return arm ? Platform.WindowsArm64 : Platform.WindowsX64; + } + + if (OperatingSystem.IsMacOS()) + { + return arm ? Platform.MacOSArm64 : Platform.MacOSX86_64; + } + + if (OperatingSystem.IsFreeBSD()) + { + return arm ? Platform.FreeBSDAarch64 : Platform.FreeBSDAmd64; + } + + var description = RuntimeInformation.OSDescription; + if (description.Contains("OpenBSD", StringComparison.OrdinalIgnoreCase)) + { + return arm ? Platform.OpenBSDAarch64 : Platform.OpenBSDAmd64; + } + + if (description.Contains("DragonFly", StringComparison.OrdinalIgnoreCase)) + { + return Platform.DragonFlyBSDAmd64; + } + + return arm ? Platform.LinuxAarch64 : Platform.LinuxAmd64; + } +} + +/// <summary>The C-family tools of a build and the features targets may turn on.</summary> +internal sealed class CCToolchain(string name, Tool c, Tool cpp, Tool linker, Tool archiver, IReadOnlyList<Feature> features) +{ + public string Name { get; } = name; + + public Tool C { get; } = c; + + public Tool Cpp { get; } = cpp; + + public Tool Linker { get; } = linker; + + public Tool Archiver { get; } = archiver; + + public IReadOnlyList<Feature> Features { get; } = features; + + /// <summary>Whether the archiver is Apple's libtool, which takes <c>-static -o</c> instead of <c>rcs</c>.</summary> + public bool ArchiverIsLibtool => + Path.GetFileNameWithoutExtension(Archiver.Program).Equals("libtool", StringComparison.Ordinal); +} + +/// <summary>The zig of a build.</summary> +internal sealed record ZigToolchain(string Name, Tool Zig); + +/// <summary>Chooses the toolchain of each family for a platform.</summary> +internal sealed class ToolchainChooser(Workspace workspace, Platform platform) +{ + private readonly Dictionary<Family, object> _chosen = []; + + public Platform Platform { get; } = platform; + + /// <summary>The C-family toolchains this build chose.</summary> + public IEnumerable<CCToolchain> UsedCC => _chosen.Values.OfType<CCToolchain>(); + + /// <summary> + /// The first toolchain the module registers for <paramref name="family"/> that runs here and builds for the platform; + /// without one, this machine's own tools, and only when the platform is this machine's. + /// </summary> + public CCToolchain CC(Family family) + { + if (_chosen.TryGetValue(family, out var known)) + { + return (CCToolchain)known; + } + + var registered = Find(family); + CCToolchain chosen; + if (registered is not null) + { + var settings = (CCToolchainSettings)registered.Settings; + var tools = settings.Tools; + var c = Required(tools.CCompiler, "CCompiler", registered); + var cpp = Required(tools.CppCompiler ?? tools.CCompiler, "CppCompiler", registered); + var linker = tools.Linker is null ? cpp : Required(tools.Linker, "Linker", registered); + var archiver = Required(tools.Archiver ?? "ar", "Archiver", registered); + chosen = new CCToolchain(registered.Label.ToString(), c, cpp, linker, archiver, settings.Features); + } + else + { + chosen = HostCC(family); + } + + _chosen[family] = chosen; + return chosen; + } + + /// <summary>The zig of the build, chosen as <see cref="CC"/> chooses.</summary> + public ZigToolchain Zig() + { + if (_chosen.TryGetValue(Family.Zig, out var known)) + { + return (ZigToolchain)known; + } + + var registered = Find(Family.Zig); + ZigToolchain chosen; + if (registered is not null) + { + var settings = (ZigToolchainSettings)registered.Settings; + chosen = new ZigToolchain(registered.Label.ToString(), Required(settings.Tools.Zig ?? "zig", "Zig", registered)); + } + else + { + RequireHost(Family.Zig); + var zig = Host.Which("zig") ?? throw new ProjectException( + "no zig on PATH; install Zig or register a Zig toolchain in MODULE.csx"); + chosen = new ZigToolchain("zig on PATH", new Tool(zig, [])); + } + + _chosen[Family.Zig] = chosen; + return chosen; + } + + private ProjectToolchain? Find(Family family) => + workspace.Registered.FirstOrDefault(toolchain => + toolchain.Family == family && toolchain.Settings switch + { + CCToolchainSettings cc => cc.ExecutionPlatform == Host.Platform && cc.TargetPlatform == Platform, + ZigToolchainSettings zig => zig.ExecutionPlatform == Host.Platform && zig.TargetPlatform == Platform, + _ => false, + }); + + private static Tool Required(string? name, string what, ProjectToolchain toolchain) + { + if (name is null) + { + throw new ProjectException($"{toolchain.Place}: the toolchain {toolchain.Label} has no {what}"); + } + + var found = Host.Which(name) + ?? throw new ProjectException($"{toolchain.Place}: the {what} '{name}' of {toolchain.Label} is not found"); + return new Tool(found, []); + } + + private void RequireHost(Family family) + { + if (Platform != Host.Platform) + { + throw new ProjectException( + $"no {FamilyName(family)} toolchain of MODULE.csx runs on {Host.Platform.Name()} and builds for " + + $"{Platform.Name()}; this machine's own tools build only for {Host.Platform.Name()}"); + } + } + + private CCToolchain HostCC(Family family) + { + RequireHost(family); + if (Host.Which("clang") is { } clang) + { + var clangxx = Host.Which("clang++") ?? clang; + var archiver = Host.Which("llvm-ar") ?? Host.Which("ar"); + if (archiver is not null) + { + return new CCToolchain("clang on PATH", new Tool(clang, []), new Tool(clangxx, []), new Tool(clangxx, []), + new Tool(archiver, []), []); + } + } + + if (family == Family.CC && Host.Which("gcc") is { } gcc && Host.Which("g++") is { } gxx && + (Host.Which("gcc-ar") ?? Host.Which("ar")) is { } ar) + { + return new CCToolchain("gcc on PATH", new Tool(gcc, []), new Tool(gxx, []), new Tool(gxx, []), new Tool(ar, []), []); + } + + if (family == Family.CC && Host.Which("zig") is { } zig) + { + return new CCToolchain("zig cc on PATH", new Tool(zig, ["cc"]), new Tool(zig, ["c++"]), new Tool(zig, ["c++"]), + new Tool(zig, ["ar"]), []); + } + + throw new ProjectException( + $"no {FamilyName(family)} compiler on PATH (clang{(family == Family.CC ? ", gcc or zig" : "")}); " + + "install one or register a toolchain in MODULE.csx"); + } + + private static string FamilyName(Family family) => family switch + { + Family.CC => "C and C++", + Family.ObjectiveC => "Objective-C", + _ => "Zig", + }; +} diff --git a/src/Progmasoft.Tazel/Driver/ZigPlanner.cs b/src/Progmasoft.Tazel/Driver/ZigPlanner.cs new file mode 100644 index 0000000..036346c --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/ZigPlanner.cs @@ -0,0 +1,315 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Driver; + +/// <summary>The Zig part of <see cref="Planner"/>: zig build-exe, build-lib and test on a root file.</summary> +internal sealed partial class Planner +{ + /// <summary>The target of zig's <c>-target</c> for a platform.</summary> + public static string ZigTriple(Platform platform) => platform switch + { + Platform.LinuxAmd64 => "x86_64-linux", + Platform.LinuxAarch64 => "aarch64-linux", + Platform.WindowsX64 => "x86_64-windows", + Platform.WindowsArm64 => "aarch64-windows", + Platform.MacOSX86_64 => "x86_64-macos", + Platform.MacOSArm64 => "aarch64-macos", + Platform.FreeBSDAmd64 => "x86_64-freebsd", + Platform.FreeBSDAarch64 => "aarch64-freebsd", + Platform.OpenBSDAmd64 => "x86_64-openbsd", + Platform.OpenBSDAarch64 => "aarch64-openbsd", + _ => "x86_64-dragonfly", + }; + + private static string OptimizationName(ZigOptimization optimization) => optimization.ToString(); + + private TargetProducts PlanZig(ProjectTarget target) + { + var products = new TargetProducts(); + if (target.Kind == TargetKind.Module) + { + // A module is compiled by what imports it; it makes nothing of its own. + return products; + } + + var settings = (ZigCompiledSettings)target.Settings; + var zig = Toolchains.Zig(); + var directory = Layout.PackageOut(target); + var defaultOptimization = Options.Mode == BuildMode.Debug ? ZigOptimization.Debug : ZigOptimization.ReleaseSafe; + var command = new List<string>(zig.Zig.Command) + { + target.Kind switch + { + TargetKind.Executable => "build-exe", + TargetKind.Test => "test", + _ => "build-lib", + }, + }; + if (target.Kind == TargetKind.SharedLibrary) + { + command.Add("-dynamic"); + } + + command.AddRange(["--cache-dir", Layout.ZigCache]); + string output; + Action? after = null; + var outputs = new List<string>(); + switch (target.Kind) + { + case TargetKind.StaticLibrary: + output = $"{directory}/{StaticLibraryName(target.Label.Name)}"; + products.Library = output; + break; + case TargetKind.SharedLibrary: + var version = ((ZigSharedLibrarySettings)settings).LibraryVersion; + var (file, linkWith, soname) = SharedLibraryNames(directory, target.Label.Name, version); + output = file; + products.Library = linkWith; + products.IsShared = true; + if (soname is not null && Options.Platform.GetOs() != Os.Windows) + { + command.Add($"-fsoname={soname}"); + } + + after = SonameLinks(file, soname, target.Label.Name); + break; + default: + output = $"{directory}/{ExecutableName(target.Label.Name)}"; + products.Executable = output; + break; + } + + command.Add($"-femit-bin={output}"); + outputs.Add(output); + var emitHeader = settings switch + { + ZigStaticLibrarySettings library => library.EmitHeader, + ZigSharedLibrarySettings library => library.EmitHeader, + _ => null, + }; + if (emitHeader is not null) + { + var header = $"{directory}/{FileSets.PathIn(emitHeader, target.PackageDirectory, target.PackageDirectory, target.Place, mustExist: false)}"; + command.Add($"-femit-h={header}"); + outputs.Add(header); + products.PublicIncludes.Add(Path.GetDirectoryName(header)!.Replace('\\', '/')); + } + + if (settings.LinkCStandardLibrary) + { + command.Add("-lc"); + } + + if (settings.StripSymbols) + { + command.Add("-fstrip"); + } + + if (settings.LinkTimeOptimization) + { + command.Add("-flto"); + } + + if (settings is ZigTestSettings test) + { + if (test.TestFilter is { } filter) + { + command.AddRange(["--test-filter", filter]); + } + + command.Add("--test-no-exec"); + } + + command.AddRange(settings.ZigCompilerOptions); + command.AddRange(Options.ZigCompilerOptions); + + // The libraries this target links, and the headers of C-family ones for @cImport. + // zig takes libraries as files and has no -Wl, so a library is linked as it is, AlwaysLink or not. + var (arguments, libraryInputs, libraryActions, sharedDirectories) = LinkLibraries(target, directory, forZig: true); + var includeDirectories = new List<string>(); + foreach (var dependency in Closure(target)) + { + Add(includeDirectories, Plan(dependency).PublicIncludes); + } + + command.AddRange(arguments); + foreach (var shared in sharedDirectories) + { + command.AddRange(["-rpath", Options.Platform.GetOs() == Os.MacOS ? "@loader_path/" + Relative(directory, shared) + : "$ORIGIN/" + Relative(directory, shared)]); + } + + command.AddRange(settings.LinkerOptions); + command.AddRange(Options.LinkerOptions); + + // Per-module options come before the -M of the module they belong to: first the root module. + var inputs = new List<string>(); + command.AddRange(ModuleOptions(target, settings, settings.OptimizationMode ?? defaultOptimization, inputs, includeDirectories)); + var cSources = FileSets.Resolve(settings.CSources, target.PackageDirectory, Layout.MainRoot, target.Place); + AddCSources(command, settings, cSources); + inputs.AddRange(cSources); + var modules = ImportedModules(target); + var names = ModuleNames(modules); + foreach (var (import, module) in target.ZigImports) + { + command.AddRange(["--dep", $"{import}={names[module]}"]); + } + + command.Add($"-Mroot={RootFile(target)}"); + foreach (var module in modules) + { + var moduleSettings = (ZigModuleSettings)module.Settings; + command.AddRange(ModuleOptions(module, moduleSettings, + moduleSettings.OptimizationMode ?? settings.OptimizationMode ?? defaultOptimization, inputs, [])); + foreach (var (import, imported) in module.ZigImports) + { + command.AddRange(["--dep", $"{import}={names[imported]}"]); + } + + command.Add($"-M{names[module]}={RootFile(module)}"); + } + + var action = new BuildAction + { + Description = $"{(target.Kind == TargetKind.Test ? "Building test" : "Compiling")} {target.Label}", + Command = command, + Directory = Layout.MainRoot, + Inputs = inputs.Concat(libraryInputs).Distinct(StringComparer.Ordinal).ToList(), + Outputs = outputs, + Environment = ActionEnvironment, + After = after, + MissingOutputHints = outputs.Skip(1).ToDictionary(header => header, _ => + "zig accepts -femit-h, and the zig compilers since 0.11 do not write the header; write it by hand and add it to Headers of a CC library"), + }; + action.Prerequisites.AddRange(libraryActions); + foreach (var dependency in Closure(target)) + { + action.Prerequisites.AddRange(Plan(dependency).HeaderActions); + } + + products.Main = action; + products.SharedLibraryDirectories.AddRange(sharedDirectories); + if (emitHeader is not null) + { + products.HeaderActions.Add(action); + } + + if (target.Kind == TargetKind.StaticLibrary) + { + products.LinkTail.AddRange(settings.LinkerOptions); + } + + return products; + } + + private static string Relative(string from, string to) => + Path.GetRelativePath(from, to).Replace('\\', '/') is var relative && relative == "." ? "" : relative; + + private string RootFile(ProjectTarget target) => + FileSets.PathIn(((ZigModuleSettings)target.Settings).RootSourceFile, target.PackageDirectory, Layout.MainRoot, + target.Place, mustExist: true); + + /// <summary>The options of one module: optimization, target, PIC and include directories; adds its files to the inputs.</summary> + private List<string> ModuleOptions( + ProjectTarget target, ZigModuleSettings settings, ZigOptimization optimization, List<string> inputs, + IReadOnlyList<string> includeDirectories) + { + var options = new List<string> { "-O", OptimizationName(optimization) }; + if (Options.Platform != Host.Platform) + { + options.AddRange(["-target", ZigTriple(Options.Platform)]); + } + + if (settings is ZigCompiledSettings { PositionIndependentCode: true }) + { + options.Add("-fPIC"); + } + + options.AddRange(includeDirectories.Select(include => "-I" + include)); + var root = RootFile(target); + inputs.Add(root); + if (settings.Sources.Items.Count > 0) + { + inputs.AddRange(FileSets.Resolve(settings.Sources, target.PackageDirectory, Layout.MainRoot, target.Place)); + } + else + { + var rootDirectory = Path.GetDirectoryName(settings.RootSourceFile)!.Replace('\\', '/'); + var pattern = rootDirectory.Length == 0 ? "**/*.zig" : $"{rootDirectory}/**/*.zig"; + inputs.AddRange(FileSets.Resolve(new Glob(pattern), target.PackageDirectory, Layout.MainRoot, target.Place)); + } + + return options; + } + + private void AddCSources(List<string> command, ZigCompiledSettings settings, IReadOnlyList<string> cSources) + { + foreach (var cxx in new[] { false, true }) + { + var files = cSources.Where(file => LanguageOf(file) is { } language && + (language is SourceLanguage.Cpp) == cxx && language != SourceLanguage.Header).ToList(); + if (files.Count == 0) + { + continue; + } + + command.Add("-cflags"); + command.AddRange(ModeFlags().Where(flag => flag != "-O2")); + command.AddRange(settings.CompilerOptions); + command.AddRange(cxx ? settings.CppCompilerOptions : settings.CCompilerOptions); + command.AddRange(Options.CompilerOptions); + command.AddRange(cxx ? Options.CppCompilerOptions : Options.CCompilerOptions); + command.Add("--"); + command.AddRange(files); + } + } + + /// <summary>Every Zig module <paramref name="target"/> imports, near or far, each once and in a fixed order.</summary> + private static List<ProjectTarget> ImportedModules(ProjectTarget target) + { + var order = new List<ProjectTarget>(); + var seen = new HashSet<ProjectTarget>(); + Visit(target); + return order; + + void Visit(ProjectTarget from) + { + foreach (var module in from.ZigImports.OrderBy(entry => entry.Key, StringComparer.Ordinal).Select(entry => entry.Value)) + { + if (seen.Add(module)) + { + order.Add(module); + Visit(module); + } + } + } + } + + /// <summary>The names the modules have on zig's command line: their target names, made unique when two clash.</summary> + private static Dictionary<ProjectTarget, string> ModuleNames(List<ProjectTarget> modules) + { + var names = new Dictionary<ProjectTarget, string>(); + var clashing = modules.GroupBy(module => module.Label.Name).Where(group => group.Count() > 1) + .SelectMany(group => group).ToHashSet(); + foreach (var module in modules) + { + names[module] = clashing.Contains(module) ? Sanitized(module.Label.ToString().TrimStart('/', '@')) : module.Label.Name; + if (names[module] == "root") + { + names[module] = "root_" + Sanitized(module.Label.Package.Path); + } + } + + return names; + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs b/src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs new file mode 100644 index 0000000..77df81c --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs @@ -0,0 +1,129 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Progmasoft.Tazel.Dsl.Custom; + +/// <summary>What is wrong with a <c>tazel_custom.txt</c> or <c>tazel_options.txt</c>, with where it is.</summary> +public sealed class CustomCommandsException : Exception +{ + /// <summary>A problem of the file.</summary> + public CustomCommandsException(string message) + : base(message) + { + } + + /// <summary>Nothing to say.</summary> + public CustomCommandsException() + { + } + + /// <summary>A problem and its cause.</summary> + public CustomCommandsException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// <summary>The constants of <c>tazel custom</c>.</summary> +public static class CustomCommandFiles +{ + /// <summary>The file that holds the commands of <c>tazel custom</c>, in the directory they run in.</summary> + public const string FileName = "tazel_custom.txt"; + + /// <summary>The most words <c>tazel custom</c> takes, those of the name of the command included.</summary> + public const int MaxArguments = 191; + + /// <summary>Ends the name of a custom command on the command line; what follows it is arguments.</summary> + public const string NameEnd = "--"; +} + +/// <summary>One argument of a program in a custom command.</summary> +public abstract record CustomArgument +{ + /// <summary>A string of the file.</summary> + /// <param name="Value">The string.</param> + public sealed record Text(string Value) : CustomArgument; + + /// <summary><c><N></c>: the Nth argument of the command line, from 1.</summary> + /// <param name="Number">N.</param> + public sealed record Position(int Number) : CustomArgument; + + /// <summary><c><*></c>: all the arguments of the command line.</summary> + public sealed record All : CustomArgument; +} + +/// <summary>One step of a custom command.</summary> +public abstract record CustomStep +{ + /// <summary> + /// A program started directly, with these arguments and no shell between; the first is the program, a string. + /// </summary> + /// <param name="Arguments">The arguments.</param> + public sealed record Program(IReadOnlyList<CustomArgument> Arguments) : CustomStep + { + /// <summary>What to start, given the arguments of the command line.</summary> + public IReadOnlyList<string> Expanded(IReadOnlyList<string> given) + { + ArgumentNullException.ThrowIfNull(given); + return Arguments.SelectMany(argument => argument switch + { + CustomArgument.Text text => [text.Value], + CustomArgument.Position position => [given[position.Number - 1]], + _ => given, + }).ToList(); + } + } + + /// <summary>A whole command line for the shell of the host: CMD on Windows, <c>sh</c> elsewhere.</summary> + /// <param name="Line">The line.</param> + public sealed record Shell(string Line) : CustomStep + { + /// <summary>What to start on this machine; the line reaches the shell unchanged.</summary> + public IReadOnlyList<string> Started(bool windows) => + windows ? ["cmd.exe", "/d", "/s", "/c", $"\"{Line}\""] : ["sh", "-c", Line]; + } +} + +/// <summary>A named command of <c>tazel_custom.txt</c>: steps that run in order until one fails.</summary> +/// <param name="Name">The words of its name, joined by one space.</param> +/// <param name="Steps">Its steps.</param> +public sealed record CustomCommand(string Name, IReadOnlyList<CustomStep> Steps) +{ + /// <summary>The words of <see cref="Name"/>.</summary> + public IReadOnlyList<string> Words => Name.Split(' '); + + /// <summary>The highest <c><N></c>: the arguments the command cannot do without.</summary> + public int Required => Placeholders.OfType<CustomArgument.Position>().Select(p => p.Number).DefaultIfEmpty(0).Max(); + + /// <summary>Whether <c><*></c> takes any number of arguments.</summary> + public bool TakesAll => Placeholders.OfType<CustomArgument.All>().Any(); + + private IEnumerable<CustomArgument> Placeholders => + Steps.OfType<CustomStep.Program>().SelectMany(program => program.Arguments); +} + +/// <summary>Finds the command a command line names.</summary> +public static class CustomCommandMatching +{ + /// <summary> + /// The command that <paramref name="words"/> name, with the arguments after its name. Names may start with other + /// names, so the longest one that fits wins. The first <c>--</c> stops the name; everything after it is an argument. + /// </summary> + public static (CustomCommand Command, IReadOnlyList<string> Arguments)? Matching( + this IReadOnlyList<CustomCommand> commands, IReadOnlyList<string> words) + { + ArgumentNullException.ThrowIfNull(commands); + ArgumentNullException.ThrowIfNull(words); + var end = words.ToList().IndexOf(CustomCommandFiles.NameEnd); + var named = end < 0 ? words.ToList() : words.Take(end).ToList(); + var after = end < 0 ? [] : words.Skip(end + 1).ToList(); + var best = commands + .Where(command => command.Words.Count <= named.Count && named.Take(command.Words.Count).SequenceEqual(command.Words)) + .MaxBy(command => command.Words.Count); + return best is null ? null : (best, named.Skip(best.Words.Count).Concat(after).ToList()); + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs b/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs new file mode 100644 index 0000000..72f8a00 --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs @@ -0,0 +1,226 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace Progmasoft.Tazel.Dsl.Custom.Lexer; + +/// <summary>The kinds of <see cref="Token"/>.</summary> +public enum TokenKind +{ + /// <summary>A word.</summary> + Name, + + /// <summary>A string in double quotes, single quotes or backticks.</summary> + String, + + /// <summary><c><N></c> or <c><*></c>; its text is what stands between the brackets.</summary> + Placeholder, + + /// <summary><c>:</c>.</summary> + Colon, + + /// <summary><c>;</c>.</summary> + Semicolon, + + /// <summary><c>(</c>.</summary> + Open, + + /// <summary><c>)</c>.</summary> + Close, +} + +/// <summary>One word of the file, with where it starts.</summary> +/// <param name="Kind">What it is.</param> +/// <param name="Text">Its text; for a string, what stands between the quotes.</param> +/// <param name="Line">Its line, from 1.</param> +/// <param name="Column">Its column, from 1.</param> +public sealed record Token(TokenKind Kind, string Text, int Line, int Column); + +/// <summary> +/// Splits the text of <c>tazel_custom.txt</c> or <c>tazel_options.txt</c>: comments go, and whitespace of any kind +/// only separates. <c>#</c> starts a comment to the end of the line, <c><# ... #></c> a comment of any length. +/// </summary> +/// <param name="text">The text.</param> +/// <param name="file">The file, for messages.</param> +public sealed class CustomLexer(string text, string file) +{ + private int _position; + private int _line = 1; + private int _column = 1; + + /// <summary>Every token of the text, in order; a character that starts no token is an error.</summary> + public IReadOnlyList<Token> Tokens() + { + var tokens = new List<Token>(); + while (_position < text.Length) + { + var letter = text[_position]; + if (char.IsWhiteSpace(letter)) + { + Advance(); + } + else if (At("<#")) + { + SkipBlockComment(); + } + else if (letter == '#') + { + while (_position < text.Length && text[_position] != '\n') + { + Advance(); + } + } + else if (letter is '"' or '\'' or '`') + { + tokens.Add(QuotedString()); + } + else if (letter == '<') + { + tokens.Add(Placeholder()); + } + else if (IsNameLetter(letter)) + { + tokens.Add(Name()); + } + else + { + var kind = letter switch + { + ':' => TokenKind.Colon, + ';' => TokenKind.Semicolon, + '(' => TokenKind.Open, + ')' => TokenKind.Close, + _ => throw Fail($"'{letter}' has no meaning here", _line, _column), + }; + tokens.Add(new Token(kind, letter.ToString(), _line, _column)); + Advance(); + } + } + + return tokens; + } + + private static bool IsNameLetter(char letter) => char.IsLetterOrDigit(letter) || letter is '-' or '_' or '.'; + + private bool At(string what) => string.CompareOrdinal(text, _position, what, 0, what.Length) == 0; + + private CustomCommandsException Fail(string message, int line, int column) => + new($"{file}:{line}:{column}: {message}"); + + private char Advance() + { + var letter = text[_position++]; + if (letter == '\n') + { + _line++; + _column = 1; + } + else + { + _column++; + } + + return letter; + } + + private void SkipBlockComment() + { + var (line, column) = (_line, _column); + Advance(); + Advance(); + while (_position < text.Length) + { + if (At("#>")) + { + Advance(); + Advance(); + return; + } + + Advance(); + } + + throw Fail("this comment has no closing #>", line, column); + } + + // A string has no escapes: it ends at the next quote of its own kind, whatever comes between. + private Token QuotedString() + { + var (line, column) = (_line, _column); + var quote = Advance(); + var begin = _position; + while (_position < text.Length && text[_position] != quote) + { + Advance(); + } + + if (_position == text.Length) + { + throw Fail($"this string has no closing {quote}", line, column); + } + + var value = text[begin.._position]; + Advance(); + return new Token(TokenKind.String, value, line, column); + } + + private Token Placeholder() + { + var (line, column) = (_line, _column); + Advance(); + var begin = _position; + while (_position < text.Length && text[_position] != '>' && !char.IsWhiteSpace(text[_position])) + { + Advance(); + } + + if (_position == text.Length || text[_position] != '>') + { + throw Fail("expected <N> or <*>", line, column); + } + + var value = text[begin.._position]; + Advance(); + var valid = value == "*" || + (value.Length > 0 && value[0] != '0' && value.Length <= 3 && IsDigits(value) && + int.Parse(value, CultureInfo.InvariantCulture) <= CustomCommandFiles.MaxArguments); + if (!valid) + { + throw Fail( + $"<{value}> is not an argument: <N> runs from 1 to {CustomCommandFiles.MaxArguments}, " + + "and <*> is all of them", + line, + column); + } + + return new Token(TokenKind.Placeholder, value, line, column); + } + + private static bool IsDigits(string value) + { + foreach (var letter in value) + { + if (letter is < '0' or > '9') + { + return false; + } + } + + return true; + } + + private Token Name() + { + var (line, column) = (_line, _column); + var begin = _position; + while (_position < text.Length && IsNameLetter(text[_position])) + { + Advance(); + } + + return new Token(TokenKind.Name, text[begin.._position], line, column); + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs new file mode 100644 index 0000000..3a3addc --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs @@ -0,0 +1,150 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using Progmasoft.Tazel.Dsl.Custom.Lexer; + +namespace Progmasoft.Tazel.Dsl.Custom.Parser; + +/// <summary>Reads the commands of a <c>tazel_custom.txt</c>.</summary> +public static class CustomParser +{ + /// <summary>The commands of the text of a <c>tazel_custom.txt</c>, in the order they are written.</summary> + public static IReadOnlyList<CustomCommand> Parse(string text, string file = CustomCommandFiles.FileName) => + new Reader(new CustomLexer(text, file).Tokens(), file).Commands(); + + private sealed class Reader(IReadOnlyList<Token> tokens, string file) + { + private int _position; + + public IReadOnlyList<CustomCommand> Commands() + { + var commands = new Dictionary<string, CustomCommand>(StringComparer.Ordinal); + var order = new List<CustomCommand>(); + while (Peek() is not null) + { + var name = Take(TokenKind.Name, "the name of a command"); + var words = new List<string> { name.Text }; + while (Peek()?.Kind == TokenKind.Name) + { + words.Add(Take(TokenKind.Name, "a word").Text); + } + + if (words.Contains(CustomCommandFiles.NameEnd)) + { + throw Fail(name, $"'{CustomCommandFiles.NameEnd}' ends a name on the command line, so a name cannot hold it"); + } + + if (words.Count > CustomCommandFiles.MaxArguments) + { + throw Fail(name, $"a name holds at most {CustomCommandFiles.MaxArguments} words"); + } + + Take(TokenKind.Colon, "':' after the name of a command"); + var steps = new List<CustomStep>(); + do + { + steps.Add(Step()); + } + while (Peek() is { Kind: not TokenKind.Semicolon }); + + Take(TokenKind.Semicolon, "';' at the end of a command"); + var joined = string.Join(' ', words); + if (commands.ContainsKey(joined)) + { + throw Fail(name, $"the command '{joined}' is defined twice"); + } + + var command = new CustomCommand(joined, steps); + if (words.Count + command.Required > CustomCommandFiles.MaxArguments) + { + throw Fail( + name, + $"'{joined}' needs {command.Required} arguments, and its name leaves room for " + + $"{CustomCommandFiles.MaxArguments - words.Count}"); + } + + commands[joined] = command; + order.Add(command); + } + + return order; + } + + private Token? Peek() => _position < tokens.Count ? tokens[_position] : null; + + private CustomCommandsException Fail(Token? token, string message) => + new($"{file}:{(token is null ? "" : $"{token.Line}:{token.Column}: ")}{message}"); + + private Token Take(TokenKind kind, string wanted) + { + var token = Peek(); + if (token?.Kind != kind) + { + throw Fail(token ?? tokens.LastOrDefault(), $"expected {wanted}"); + } + + _position++; + return token; + } + + private List<Token> Values() + { + var values = new List<Token>(); + while (Peek() is { Kind: TokenKind.String or TokenKind.Placeholder } token) + { + values.Add(Take(token.Kind, "a string")); + } + + return values; + } + + private static CustomArgument ArgumentOf(Token token) => + token.Kind == TokenKind.String ? new CustomArgument.Text(token.Text) + : token.Text == "*" ? new CustomArgument.All() + : new CustomArgument.Position(int.Parse(token.Text, CultureInfo.InvariantCulture)); + + private CustomStep Step() + { + var shell = Peek() is { Kind: TokenKind.Name, Text: "s" }; + if (shell) + { + _position++; + } + + var open = Take(TokenKind.Open, "'(' of a command"); + var values = Values(); + Take(TokenKind.Close, "')' after the strings of a command"); + if (shell) + { + var placeholder = values.FirstOrDefault(value => value.Kind == TokenKind.Placeholder); + if (placeholder is not null) + { + throw Fail(placeholder, "s(...) takes no arguments; (...) passes them"); + } + + if (values.Count != 1) + { + throw Fail(open, "s(...) takes one string, the whole command line: s(\"npm dev\")"); + } + + return new CustomStep.Shell(values[0].Text); + } + + if (values.Count == 0) + { + throw Fail(open, "a command names at least a program"); + } + + if (values[0].Kind != TokenKind.String) + { + throw Fail(values[0], "a command starts with the name of its program"); + } + + return new CustomStep.Program(values.Select(ArgumentOf).ToList()); + } + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs new file mode 100644 index 0000000..4b19b9f --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs @@ -0,0 +1,261 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Dsl.Custom; +using Progmasoft.Tazel.Dsl.Custom.Lexer; + +namespace Progmasoft.Tazel.Dsl.Options; + +/// <summary>How much of something a MicroVM gets: as much as Tazel chooses, or exactly an amount.</summary> +/// <param name="Amount">The amount, or null for automatic.</param> +public sealed record Allocation(int? Amount) +{ + /// <summary>As much as Tazel chooses for this machine.</summary> + public static Allocation Auto { get; } = new((int?)null); +} + +/// <summary>The options of <c>tazel_options.txt</c>; each one not written keeps its default.</summary> +public sealed record TazelOptions +{ + /// <summary>The file of the options of Tazel, in a directory a command runs in or above it.</summary> + public const string FileName = "tazel_options.txt"; + + /// <summary> + /// Whether what a project brings to run, custom commands and the build among it, runs inside a MicroVM. + /// </summary> + public bool SandboxingWithMicrovm { get; init; } + + /// <summary>Whether the MicroVM reaches the network.</summary> + public bool MicrovmNetwork { get; init; } + + /// <summary>The memory of the MicroVM, in MiB.</summary> + public Allocation MicrovmMemory { get; init; } = Allocation.Auto; + + /// <summary>The processors of the MicroVM.</summary> + public Allocation MicrovmCpus { get; init; } = Allocation.Auto; + + /// <summary>The platform commands build for unless <c>--platform</c> names one; default: the host's.</summary> + public Platform? Platform { get; init; } +} + +/// <summary>What is wrong with a <c>tazel_options.txt</c>, with where it is.</summary> +public sealed class TazelOptionsException : Exception +{ + /// <summary>A problem of the file.</summary> + public TazelOptionsException(string message) + : base(message) + { + } + + /// <summary>Nothing to say.</summary> + public TazelOptionsException() + { + } + + /// <summary>A problem and its cause.</summary> + public TazelOptionsException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// <summary>Reads and finds <c>tazel_options.txt</c>.</summary> +public static class TazelOptionsFile +{ + private const int MinMemory = 256; + private const int MaxMemory = 1_048_576; + private const int MaxCpus = 256; + + private static readonly string[] Keys = + ["sandboxing-with-microvm", "microvm-network", "microvm-memory", "microvm-cpus", "platform"]; + + /// <summary> + /// Reads the text of a <c>tazel_options.txt</c>, with the comments and strings of <c>tazel_custom.txt</c>; + /// <paramref name="file"/> names it in messages. + /// </summary> + public static TazelOptions Parse(string text, string file = TazelOptions.FileName) + { + IReadOnlyList<Token> tokens; + try + { + tokens = new CustomLexer(text, file).Tokens(); + } + catch (CustomCommandsException error) + { + throw new TazelOptionsException(error.Message, error); + } + + return new Reader(tokens, file).Options(); + } + + /// <summary>Every <c>tazel_options.txt</c> at or above <paramref name="directory"/>, the nearest first.</summary> + public static IReadOnlyList<string> Find(string directory) + { + var found = new List<string>(); + for (var current = new DirectoryInfo(Path.GetFullPath(directory)); current is not null; current = current.Parent) + { + var file = Path.Combine(current.FullName, TazelOptions.FileName); + // A file that cannot be inspected is an error, never a file that is not there, so a sandbox is not skipped. + FileAttributes attributes; + try + { + attributes = File.GetAttributes(file); + } + catch (FileNotFoundException) + { + continue; + } + catch (DirectoryNotFoundException) + { + continue; + } + catch (IOException problem) + { + throw new TazelOptionsException($"{file} could not be inspected: {problem.Message}", problem); + } + catch (UnauthorizedAccessException problem) + { + throw new TazelOptionsException($"{file} could not be inspected: {problem.Message}", problem); + } + + if ((attributes & FileAttributes.Directory) == 0) + { + found.Add(file); + } + } + + return found; + } + + /// <summary> + /// The options that hold in <paramref name="directory"/>: those of the nearest file, except that a sandbox asked + /// for in any file above stays asked for, so a project cannot turn off what a directory around it requires. + /// Default options, and no file, without any. + /// </summary> + public static (TazelOptions Options, string? SandboxFile) Effective(string directory) + { + var files = Find(directory).Select(file => (File: file, Options: Read(file))).ToList(); + if (files.Count == 0) + { + return (new TazelOptions(), null); + } + + var asking = files.FirstOrDefault(entry => entry.Options.SandboxingWithMicrovm).File; + return (files[0].Options with { SandboxingWithMicrovm = asking is not null }, asking); + } + + private static TazelOptions Read(string file) + { + string text; + try + { + text = File.ReadAllText(file); + } + catch (IOException problem) + { + throw new TazelOptionsException($"{file} could not be read: {problem.Message}", problem); + } + catch (UnauthorizedAccessException problem) + { + throw new TazelOptionsException($"{file} could not be read: {problem.Message}", problem); + } + + return Parse(text, file); + } + + private sealed class Reader(IReadOnlyList<Token> tokens, string file) + { + private int _position; + + public TazelOptions Options() + { + var options = new TazelOptions(); + var seen = new HashSet<string>(StringComparer.Ordinal); + while (_position < tokens.Count) + { + var key = Take(TokenKind.Name, "the name of an option"); + if (!Keys.Contains(key.Text, StringComparer.Ordinal)) + { + throw Fail(key, $"'{key.Text}' is not an option; the options are {string.Join(", ", Keys)}"); + } + + if (!seen.Add(key.Text)) + { + throw Fail(key, $"'{key.Text}' is set twice"); + } + + Take(TokenKind.Colon, $"':' after {key.Text}"); + if (_position >= tokens.Count || tokens[_position].Kind is not (TokenKind.Name or TokenKind.String)) + { + throw Fail(_position < tokens.Count ? tokens[_position] : key, $"expected a value for {key.Text}"); + } + + var value = tokens[_position++]; + options = key.Text switch + { + "sandboxing-with-microvm" => options with { SandboxingWithMicrovm = Boolean(value) }, + "microvm-network" => options with { MicrovmNetwork = Boolean(value) }, + "microvm-memory" => options with { MicrovmMemory = Amount(value, MinMemory, MaxMemory, "MiB") }, + "microvm-cpus" => options with { MicrovmCpus = Amount(value, 1, MaxCpus, "processors") }, + _ => options with { Platform = PlatformOf(value) }, + }; + + // The last option may end the file without a ';'. + if (_position < tokens.Count) + { + Take(TokenKind.Semicolon, $"';' after the value of {key.Text}"); + } + } + + return options; + } + + private TazelOptionsException Fail(Token token, string message) => + new($"{file}:{token.Line}:{token.Column}: {message}"); + + private Token Take(TokenKind kind, string wanted) + { + if (_position >= tokens.Count || tokens[_position].Kind != kind) + { + throw Fail(_position < tokens.Count ? tokens[_position] : tokens[^1], $"expected {wanted}"); + } + + return tokens[_position++]; + } + + private bool Boolean(Token value) => value is { Kind: TokenKind.Name, Text: "true" } ? true + : value is { Kind: TokenKind.Name, Text: "false" } ? false + : throw Fail(value, "expected true or false"); + + // "auto" is a string, in any of the three quotes; a number stands bare. + private Allocation Amount(Token value, int min, int max, string unit) + { + if (value.Kind == TokenKind.String) + { + return value.Text == "auto" ? Allocation.Auto : throw Fail(value, "the only string here is \"auto\""); + } + + if (value.Text.Length == 0 || value.Text[0] == '0' || value.Text.Length > 9 || + !value.Text.All(char.IsAsciiDigit)) + { + throw Fail(value, $"expected a number of {unit} or \"auto\""); + } + + var amount = int.Parse(value.Text, CultureInfo.InvariantCulture); + return amount < min || amount > max + ? throw Fail(value, $"{amount} is outside {min} to {max} {unit}") + : new Allocation(amount); + } + + private Platform PlatformOf(Token value) => + value.Kind == TokenKind.Name && Platforms.TryParse(value.Text, out var platform) + ? platform + : throw Fail(value, $"'{value.Text}' is not a platform; the platforms are {string.Join(", ", Platforms.Names)}"); + } +} diff --git a/src/Progmasoft.Tazel/Label/Labels.cs b/src/Progmasoft.Tazel/Label/Labels.cs new file mode 100644 index 0000000..2e6d8b5 --- /dev/null +++ b/src/Progmasoft.Tazel/Label/Labels.cs @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Text.RegularExpressions; + +namespace Progmasoft.Tazel.Label; + +/// <summary>A label that cannot be read, with the reason.</summary> +public sealed class LabelException : Exception +{ + /// <summary>A label that cannot be read.</summary> + public LabelException(string message) + : base(message) + { + } + + /// <summary>Nothing to say.</summary> + public LabelException() + { + } + + /// <summary>A problem and its cause.</summary> + public LabelException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// <summary> +/// A package: the directory of one <c>BUILD.csx</c>, relative to the root of its module, in this module +/// (<see cref="Repository"/> null) or a dependency (its name, alias or local module name). +/// </summary> +/// <param name="Repository">The dependency, or null for this module.</param> +/// <param name="Path">The directory, with <c>/</c> between its parts; empty for the root package.</param> +public sealed record PackageId(string? Repository, string Path) +{ + /// <summary>The root package of this module.</summary> + public static PackageId Root { get; } = new(null, ""); + + /// <summary><c>//dir</c> or <c>@name//dir</c>; the root package is <c>//</c>.</summary> + public override string ToString() => $"{(Repository is null ? "" : "@" + Repository)}//{Path}"; +} + +/// <summary>What a command selects: one target, or every target of some packages.</summary> +public abstract record Selection; + +/// <summary>One target: <c>//dir:name</c>, <c>//:name</c>, <c>@dep//dir:name</c>.</summary> +/// <param name="Package">Its package.</param> +/// <param name="Name">Its name.</param> +public sealed record TargetLabel(PackageId Package, string Name) : Selection +{ + /// <inheritdoc/> + public override string ToString() => $"{Package}:{Name}"; +} + +/// <summary><c>//dir/...</c>: the package and every package below it; <c>//...</c> is the whole module.</summary> +/// <param name="Package">The package the pattern starts at.</param> +public sealed record PackagePattern(PackageId Package) : Selection +{ + /// <summary>Whether <paramref name="other"/> is this package or one below it.</summary> + public bool Covers(PackageId other) + { + ArgumentNullException.ThrowIfNull(other); + return other.Repository == Package.Repository && + (Package.Path.Length == 0 || other.Path == Package.Path || + other.Path.StartsWith(Package.Path + "/", StringComparison.Ordinal)); + } + + /// <inheritdoc/> + public override string ToString() => Package.Path.Length == 0 ? $"{Package}..." : $"{Package}/..."; +} + +/// <summary>Reads labels as Bazel spells them; nothing else is a label.</summary> +public static partial class Labels +{ + /// <summary>A target label; <c>:name</c> is a target of <paramref name="current"/>. Patterns are refused.</summary> + public static TargetLabel Target(string text, PackageId current) => + Selection(text, current) switch + { + TargetLabel label => label, + _ => throw new LabelException($"'{text}' names packages, not one target; write //dir:name"), + }; + + /// <summary>A target label or a package pattern; <c>:name</c> is a target of <paramref name="current"/>.</summary> + public static Selection Selection(string text, PackageId current) + { + ArgumentNullException.ThrowIfNull(text); + ArgumentNullException.ThrowIfNull(current); + if (text.StartsWith(':')) + { + return new TargetLabel(current, Checked(text[1..], "target name", text)); + } + + string? repository = null; + var rest = text; + if (text.StartsWith('@')) + { + var slashes = text.IndexOf("//", StringComparison.Ordinal); + if (slashes < 0) + { + throw new LabelException($"'{text}' has no //; write @name//:target"); + } + + repository = Checked(text[1..slashes], "dependency name", text); + rest = text[slashes..]; + } + + if (!rest.StartsWith("//", StringComparison.Ordinal)) + { + throw new LabelException($"'{text}' is not a label; write //dir:name, //:name or :name"); + } + + var body = rest[2..]; + if (body == "...") + { + return new PackagePattern(new PackageId(repository, "")); + } + + if (body.EndsWith("/...", StringComparison.Ordinal)) + { + return new PackagePattern(new PackageId(repository, PackagePath(body[..^4], text))); + } + + var colon = body.LastIndexOf(':'); + if (colon < 0) + { + var shown = body.TrimEnd('/'); + var last = shown[(shown.LastIndexOf('/') + 1)..]; + throw new LabelException($"'{text}' names no target; write //{shown}:{last} or //{shown}/..."); + } + + var directory = body[..colon]; + if (directory.EndsWith('/')) + { + throw new LabelException($"'{text}': no / before the colon; write //{directory.TrimEnd('/')}:..."); + } + + var path = directory.Length == 0 ? "" : PackagePath(directory, text); + return new TargetLabel(new PackageId(repository, path), Checked(body[(colon + 1)..], "target name", text)); + } + + /// <summary>Checks a target or package name as a project file writes it.</summary> + public static bool IsName(string name) => NamePattern().IsMatch(name); + + private static string PackagePath(string path, string text) + { + if (path.Length == 0) + { + throw new LabelException($"'{text}' has an empty package"); + } + + foreach (var segment in path.Split('/')) + { + if (segment is "." or "..") + { + throw new LabelException($"'{text}': a package path has no . or .. parts"); + } + + Checked(segment, "package directory", text); + } + + return path; + } + + private static string Checked(string name, string what, string text) + { + if (!IsName(name)) + { + throw new LabelException( + $"'{text}': the {what} '{name}' must be letters, digits and _ + . -"); + } + + return name; + } + + [GeneratedRegex("^[A-Za-z0-9_+.-]+$")] + private static partial Regex NamePattern(); +} diff --git a/src/Progmasoft.Tazel/Output/Reporter.cs b/src/Progmasoft.Tazel/Output/Reporter.cs new file mode 100644 index 0000000..191d3e4 --- /dev/null +++ b/src/Progmasoft.Tazel/Output/Reporter.cs @@ -0,0 +1,205 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Linq; +using Spectre.Console; + +namespace Progmasoft.Tazel.Output; + +/// <summary>When colors or the progress counter are shown.</summary> +internal enum When +{ + /// <summary>When the output is a terminal.</summary> + Auto, + + /// <summary>Always.</summary> + Always, + + /// <summary>Never.</summary> + Never, +} + +/// <summary>How a test ended.</summary> +internal enum TestStatus +{ + Passed, + Failed, + TimedOut, + Flaky, + NotBuilt, +} + +/// <summary>One line of the summary of <c>tazel test</c>.</summary> +internal sealed record TestOutcome(string Label, TestStatus Status, TimeSpan Duration, string Log); + +/// <summary>Everything Tazel prints, through Spectre.Console; it is safe to call from the jobs of a build.</summary> +internal sealed class Reporter +{ + private readonly object _lock = new(); + private readonly bool _quiet; + private readonly bool _counter; + + public Reporter(IAnsiConsole console, bool quiet, When progress) + { + Console = console; + _quiet = quiet; + _counter = progress == When.Always || (progress == When.Auto && !quiet && console.Profile.Capabilities.Interactive); + } + + public IAnsiConsole Console { get; } + + /// <summary>A console with the colors that <paramref name="color"/> asks for.</summary> + public static IAnsiConsole CreateConsole(When color, System.IO.TextWriter? output = null) + { + var console = AnsiConsole.Create(new AnsiConsoleSettings + { + Ansi = color switch + { + When.Always => AnsiSupport.Yes, + When.Never => AnsiSupport.No, + _ => AnsiSupport.Detect, + }, + ColorSystem = color == When.Never ? ColorSystemSupport.NoColors : ColorSystemSupport.Detect, + Out = output is null ? null : new AnsiConsoleOutput(output), + }); + + // Lines that go to a file or a pipe are not wrapped: a command line stays one line. + if (output is not null || System.Console.IsOutputRedirected) + { + console.Profile.Width = 4096; + } + + return console; + } + + /// <summary>A status line, such as what is being loaded; <c>--quiet</c> drops it.</summary> + public void Status(string text) + { + if (!_quiet) + { + Write($"[blue]INFO[/] {Markup.Escape(text)}"); + } + } + + /// <summary>An action finished; its output, when it printed any, follows it.</summary> + public void ActionDone(int done, int total, string description, string output) + { + if (_quiet && output.Length == 0) + { + return; + } + + var counter = _counter ? $"[grey][[{done}/{total}]][/] " : ""; + lock (_lock) + { + if (!_quiet || output.Length > 0) + { + Console.MarkupLine($"{counter}{Markup.Escape(description)}"); + } + + if (output.Length > 0) + { + Console.WriteLine(output.TrimEnd('\n')); + } + } + } + + /// <summary>An action failed, with its command line and what it printed.</summary> + public void ActionFailed(string description, IReadOnlyList<string> command, string output) + { + lock (_lock) + { + Console.MarkupLine($"[red bold]FAILED[/] {Markup.Escape(description)}"); + Console.MarkupLine($"[grey]{Markup.Escape(Quote(command))}[/]"); + if (output.Length > 0) + { + Console.WriteLine(output.TrimEnd('\n')); + } + } + } + + /// <summary>What went wrong, ending the command.</summary> + public void Error(string message) + { + lock (_lock) + { + Console.MarkupLine($"[red bold]error[/]: {Markup.Escape(message)}"); + } + } + + /// <summary>Something the user should know that does not stop the command.</summary> + public void Warning(string message) => Write($"[yellow]warning[/]: {Markup.Escape(message)}"); + + /// <summary>The end of a build.</summary> + public void Success(string message) + { + if (!_quiet) + { + Write($"[green]{Markup.Escape(message)}[/]"); + } + } + + /// <summary>The summary of <c>tazel test</c>, a table of the tests and how each ended.</summary> + public void TestSummary(IReadOnlyList<TestOutcome> outcomes) + { + ArgumentNullException.ThrowIfNull(outcomes); + var table = new Table().Border(TableBorder.Rounded).AddColumn("Test").AddColumn("Result").AddColumn(new TableColumn("Time").RightAligned()); + foreach (var outcome in outcomes) + { + var status = outcome.Status switch + { + TestStatus.Passed => "[green]PASSED[/]", + TestStatus.Flaky => "[yellow]FLAKY[/]", + TestStatus.TimedOut => "[red]TIMEOUT[/]", + TestStatus.NotBuilt => "[red]NOT BUILT[/]", + _ => "[red]FAILED[/]", + }; + table.AddRow(Markup.Escape(outcome.Label), status, $"{outcome.Duration.TotalSeconds:0.0} s"); + } + + lock (_lock) + { + Console.Write(table); + var failed = outcomes.Count(o => o.Status is TestStatus.Failed or TestStatus.TimedOut or TestStatus.NotBuilt); + Console.MarkupLine(failed == 0 + ? $"[green]{outcomes.Count} test{(outcomes.Count == 1 ? "" : "s")} passed[/]" + : $"[red]{failed} of {outcomes.Count} test{(outcomes.Count == 1 ? "" : "s")} failed[/]"); + } + } + + /// <summary>The output of a test that failed.</summary> + public void TestLog(string label, string log) + { + lock (_lock) + { + Console.MarkupLine($"[red]--- {Markup.Escape(label)} ---[/]"); + Console.WriteLine(log.TrimEnd('\n')); + } + } + + /// <summary>Plain text, as help prints it.</summary> + public void Plain(string text) + { + lock (_lock) + { + Console.WriteLine(text); + } + } + + /// <summary>A command line as a shell would take it, for messages.</summary> + public static string Quote(IEnumerable<string> command) => + string.Join(' ', command.Select(part => + part.Length > 0 && part.All(c => char.IsAsciiLetterOrDigit(c) || "-_./=:,+@%".Contains(c, StringComparison.Ordinal)) + ? part + : "'" + part.Replace("'", "'\\''", StringComparison.Ordinal) + "'")); + + private void Write(string markup) + { + lock (_lock) + { + Console.MarkupLine(markup); + } + } +} diff --git a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj new file mode 100644 index 0000000..e08f47b --- /dev/null +++ b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj @@ -0,0 +1,26 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<!-- The tazel command. --> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <OutputType>Exe</OutputType> + <AssemblyName>tazel</AssemblyName> + <RootNamespace>Progmasoft.Tazel</RootNamespace> + <ServerGarbageCollection>false</ServerGarbageCollection> + <TieredPGO>true</TieredPGO> + </PropertyGroup> + <ItemGroup> + <ProjectReference Include="../Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Spectre.Console" /> + <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" /> + <PackageReference Include="NuGet.Versioning" /> + <PackageReference Include="Lzma.Net" /> + </ItemGroup> + <ItemGroup> + <InternalsVisibleTo Include="Progmasoft.Tazel.Tests" /> + <InternalsVisibleTo Include="Progmasoft.Tazel.Benchmarks" /> + <InternalsVisibleTo Include="Progmasoft.Tazel.Fuzz" /> + </ItemGroup> +</Project> diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs new file mode 100644 index 0000000..f100ac1 --- /dev/null +++ b/src/Progmasoft.Tazel/Program.cs @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Dsl.Custom; +using Progmasoft.Tazel.Dsl.Options; +using Progmasoft.Tazel.Label; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel; + +/// <summary>The tazel command.</summary> +internal static class Program +{ + /// <summary>Exit status of a command line Tazel cannot take.</summary> + public const int UsageError = 2; + + private static async Task<int> Main(string[] arguments) + { + using var cancel = new CancellationTokenSource(); + Console.CancelKeyPress += (_, press) => + { + press.Cancel = true; + cancel.Cancel(); + }; + return await RunAsync(arguments, Directory.GetCurrentDirectory(), null, cancel.Token).ConfigureAwait(false); + } + + /// <summary>Runs one command line in <paramref name="directory"/>; tests give <paramref name="output"/>.</summary> + public static async Task<int> RunAsync(string[] arguments, string directory, TextWriter? output, CancellationToken cancel) + { + Command command; + try + { + command = CommandLine.Parse(arguments); + } + catch (CommandLineException error) + { + new Reporter(Reporter.CreateConsole(When.Auto, output), quiet: false, When.Never).Error(error.Message); + return UsageError; + } + + var reporter = new Reporter(Reporter.CreateConsole(command.Output.Color, output), command.Output.Quiet, command.Output.Progress); + try + { + return await new Commands(reporter, directory).RunAsync(command, cancel).ConfigureAwait(false); + } + catch (CommandLineException error) + { + reporter.Error(error.Message); + return UsageError; + } + catch (Exception error) when (error is ProjectException or LabelException or TazelOptionsException or + CustomCommandsException) + { + reporter.Error(error.Message); + return 1; + } + catch (OperationCanceledException) + { + reporter.Error("stopped"); + return 130; + } + } +} diff --git a/src/Progmasoft.Tazel/Project/FileSets.cs b/src/Progmasoft.Tazel/Project/FileSets.cs new file mode 100644 index 0000000..5aac65f --- /dev/null +++ b/src/Progmasoft.Tazel/Project/FileSets.cs @@ -0,0 +1,198 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Progmasoft.Tazel.Dsl.Common; + +namespace Progmasoft.Tazel.Project; + +/// <summary> +/// Turns the files a project file names into paths relative to the root of the main module, which is where every +/// command of a build runs. A glob does not reach into a subpackage, a directory with a project file of its own. +/// </summary> +internal static class FileSets +{ + /// <summary>The files of <paramref name="files"/>, in the package at <paramref name="packageDirectory"/>.</summary> + public static IReadOnlyList<string> Resolve(Files files, string packageDirectory, string mainRoot, string place) + { + ArgumentNullException.ThrowIfNull(files); + var result = new List<string>(); + var seen = new HashSet<string>(StringComparer.Ordinal); + foreach (var item in files.Items) + { + IEnumerable<string> found = item.Path is { } path + ? [OnePath(path, packageDirectory, place)] + : Expand(item.Glob!, packageDirectory, place); + foreach (var relative in found) + { + var shown = ToRoot(Path.Combine(packageDirectory, relative), mainRoot); + if (seen.Add(shown)) + { + result.Add(shown); + } + } + } + + return result; + } + + /// <summary>One path of a package, checked to stay inside it, relative to the main module root.</summary> + public static string PathIn(string path, string packageDirectory, string mainRoot, string place, bool mustExist) + { + var relative = Checked(path, place); + var full = Path.Combine(packageDirectory, relative); + if (mustExist && !File.Exists(full) && !Directory.Exists(full)) + { + throw new ProjectException($"{place}: '{path}' does not exist"); + } + + return ToRoot(full, mainRoot); + } + + /// <summary><paramref name="full"/> relative to <paramref name="mainRoot"/>, with <c>/</c> between its parts.</summary> + public static string ToRoot(string full, string mainRoot) => + Path.GetRelativePath(mainRoot, full).Replace('\\', '/'); + + /// <summary>Whether <paramref name="relative"/>, with <c>/</c> between its parts, matches <paramref name="pattern"/>.</summary> + public static bool Matches(string pattern, string relative) => + MatchParts(pattern.Split('/'), 0, relative.Split('/'), 0); + + private static string OnePath(string path, string packageDirectory, string place) + { + var relative = Checked(path, place); + if (!File.Exists(Path.Combine(packageDirectory, relative))) + { + throw new ProjectException($"{place}: '{path}' does not exist"); + } + + return relative; + } + + private static string Checked(string path, string place) + { + if (path.Length == 0 || Path.IsPathRooted(path) || path.Contains('\\', StringComparison.Ordinal)) + { + throw new ProjectException($"{place}: '{path}' must be a path below the project file, with / between its parts"); + } + + foreach (var part in path.Split('/')) + { + if (part is "" or "." or "..") + { + throw new ProjectException($"{place}: '{path}' must stay below the project file; it has no . or .. parts"); + } + } + + return path; + } + + private static List<string> Expand(Glob glob, string packageDirectory, string place) + { + Checked(glob.Pattern, place); + var all = new List<string>(); + Walk(packageDirectory, "", all, top: true); + return all + .Where(file => Matches(glob.Pattern, file) && !glob.Exclude.Any(pattern => Matches(pattern, file))) + .Order(StringComparer.Ordinal) + .ToList(); + } + + private static void Walk(string directory, string prefix, List<string> found, bool top) + { + if (!top && ModuleFiles.BuildFileIn(directory) is not null) + { + return; + } + + foreach (var entry in new DirectoryInfo(directory).EnumerateFileSystemInfos()) + { + if (entry.Name.StartsWith('.') || entry.LinkTarget is not null) + { + continue; + } + + if (entry is DirectoryInfo) + { + if (!File.Exists(Path.Combine(entry.FullName, ModuleFiles.ModuleFile))) + { + Walk(entry.FullName, prefix + entry.Name + "/", found, top: false); + } + } + else + { + found.Add(prefix + entry.Name); + } + } + } + + private static bool MatchParts(string[] pattern, int p, string[] path, int i) + { + while (p < pattern.Length) + { + if (pattern[p] == "**") + { + for (var skip = i; skip <= path.Length; skip++) + { + if (MatchParts(pattern, p + 1, path, skip)) + { + return true; + } + } + + return false; + } + + if (i >= path.Length || !MatchName(pattern[p], 0, path[i], 0)) + { + return false; + } + + p++; + i++; + } + + return i == path.Length; + } + + private static bool MatchName(string pattern, int p, string name, int n) + { + while (p < pattern.Length) + { + switch (pattern[p]) + { + case '*': + for (var skip = n; skip <= name.Length; skip++) + { + if (MatchName(pattern, p + 1, name, skip)) + { + return true; + } + } + + return false; + case '?': + if (n >= name.Length) + { + return false; + } + + break; + default: + if (n >= name.Length || name[n] != pattern[p]) + { + return false; + } + + break; + } + + p++; + n++; + } + + return n == name.Length; + } +} diff --git a/src/Progmasoft.Tazel/Project/LocalModules.cs b/src/Progmasoft.Tazel/Project/LocalModules.cs new file mode 100644 index 0000000..9e8199d --- /dev/null +++ b/src/Progmasoft.Tazel/Project/LocalModules.cs @@ -0,0 +1,101 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.Dsl.Module.Prelude; + +namespace Progmasoft.Tazel.Project; + +/// <summary>The archives a module names with <c>LocalModule.From</c>, checked and unpacked.</summary> +internal static class LocalModules +{ + /// <summary> + /// Checks the archive of <paramref name="local"/> against its SHA-256 and unpacks it once below the state directory of + /// <paramref name="mainRoot"/>; returns the root of the module in it. + /// </summary> + public static string Unpack(string mainRoot, string moduleRoot, LocalModuleSettings local, string place) + { + if (local.Include.Length == 0 || Path.IsPathRooted(local.Include) || local.Include.Contains('*', StringComparison.Ordinal)) + { + throw new ProjectException($"{place}: Include names one archive by its path in the module, without a glob"); + } + + if (!local.Include.EndsWith(ModuleArchive.Extension, StringComparison.Ordinal)) + { + throw new ProjectException($"{place}: '{local.Include}' is not a {ModuleArchive.Extension} archive"); + } + + var archive = Path.Combine(moduleRoot, local.Include); + if (!File.Exists(archive)) + { + throw new ProjectException($"{place}: '{local.Include}' does not exist"); + } + + var expected = Expected(moduleRoot, local, place); + var actual = Sha256Sums.Sha256(archive); + if (!string.Equals(expected, actual, StringComparison.Ordinal)) + { + throw new ProjectException($"{place}: '{local.Include}' has the SHA-256 {actual}, not {expected}"); + } + + var destination = Path.Combine(mainRoot, ModuleFiles.StateDirectory, "external", $"{local.Name}-{actual[..16]}"); + var marker = Path.Combine(destination, ".unpacked"); + if (File.Exists(marker)) + { + return File.ReadAllText(marker).Trim() is { Length: > 0 } top + ? Path.Combine(destination, top) + : throw new ProjectException($"{destination} is damaged; remove it"); + } + + if (Directory.Exists(destination)) + { + Directory.Delete(destination, recursive: true); + } + + var root = ModuleArchive.Unpack(archive, destination); + File.WriteAllText(marker, Path.GetFileName(root)); + return root; + } + + private static string Expected(string moduleRoot, LocalModuleSettings local, string place) + { + if ((local.Sha256 is null) == (local.Sha256Sums is null)) + { + throw new ProjectException($"{place}: '{local.Name}' needs Sha256 or Sha256Sums, one of them"); + } + + if (local.Sha256 is { } sha) + { + if (sha.Length != 64 || !Uri.IsHexDigit(sha[0]) || !IsHex(sha)) + { + throw new ProjectException($"{place}: '{sha}' is not a SHA-256 of 64 hexadecimal digits"); + } + + return sha.ToLowerInvariant(); + } + + var sums = Path.Combine(moduleRoot, local.Sha256Sums!); + if (!File.Exists(sums)) + { + throw new ProjectException($"{place}: '{local.Sha256Sums}' does not exist"); + } + + return Sha256Sums.SumFor(File.ReadAllText(sums), Path.GetFileName(local.Include), local.Sha256Sums!) + ?? throw new ProjectException($"{place}: '{local.Sha256Sums}' does not name {Path.GetFileName(local.Include)}"); + } + + private static bool IsHex(string text) + { + foreach (var letter in text) + { + if (!Uri.IsHexDigit(letter)) + { + return false; + } + } + + return true; + } +} diff --git a/src/Progmasoft.Tazel/Project/ModuleFiles.cs b/src/Progmasoft.Tazel/Project/ModuleFiles.cs new file mode 100644 index 0000000..0150b40 --- /dev/null +++ b/src/Progmasoft.Tazel/Project/ModuleFiles.cs @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace Progmasoft.Tazel.Project; + +/// <summary>Where the project files of a module are.</summary> +internal static class ModuleFiles +{ + /// <summary>The file at the root of a module.</summary> + public const string ModuleFile = "MODULE.csx"; + + /// <summary>The directory below the root where Tazel keeps what it makes.</summary> + public const string StateDirectory = ".tazel"; + + /// <summary>The names a package's project file may have, in the order they are looked for; the first wins.</summary> + public static IReadOnlyList<string> BuildFileNames { get; } = + ["BUILD.csx", "BUILD.tzl", "BUILD.tazel", "BUILD", "Tazel.build"]; + + /// <summary>The root of the module <paramref name="directory"/> is in: the nearest directory with a MODULE.csx.</summary> + public static string FindRoot(string directory) + { + for (var current = new DirectoryInfo(Path.GetFullPath(directory)); current is not null; current = current.Parent) + { + if (File.Exists(Path.Combine(current.FullName, ModuleFile))) + { + return current.FullName; + } + } + + throw new ProjectException($"there is no {ModuleFile} in {Path.GetFullPath(directory)} or above it"); + } + + /// <summary>The project file of the package at <paramref name="directory"/>, or null when it has none.</summary> + public static string? BuildFileIn(string directory) + { + // The lookup is case-sensitive on every system, so build.csx is not a project file anywhere. + var names = new HashSet<string>( + Directory.EnumerateFiles(directory).Select(Path.GetFileName).OfType<string>(), StringComparer.Ordinal); + return BuildFileNames.FirstOrDefault(names.Contains) is { } name ? Path.Combine(directory, name) : null; + } + + /// <summary> + /// Every package of the module at <paramref name="root"/>, by its path: directories with a project file, less + /// hidden ones and the directories of other modules. + /// </summary> + public static IReadOnlyList<(string Path, string File)> Packages(string root) + { + var found = new List<(string, string)>(); + Visit(root, ""); + return found.OrderBy(entry => entry.Item1, StringComparer.Ordinal).ToList(); + + void Visit(string directory, string path) + { + if (BuildFileIn(directory) is { } file) + { + found.Add((path, file)); + } + + foreach (var child in new DirectoryInfo(directory).EnumerateDirectories()) + { + if (child.Name.StartsWith('.') || child.LinkTarget is not null || + File.Exists(Path.Combine(child.FullName, ModuleFile))) + { + continue; + } + + Visit(child.FullName, path.Length == 0 ? child.Name : $"{path}/{child.Name}"); + } + } + } +} diff --git a/src/Progmasoft.Tazel/Project/ScriptHost.cs b/src/Progmasoft.Tazel/Project/ScriptHost.cs new file mode 100644 index 0000000..e944513 --- /dev/null +++ b/src/Progmasoft.Tazel/Project/ScriptHost.cs @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Scripting; +using Microsoft.CodeAnalysis.Scripting; +using Progmasoft.Tazel.Dsl; + +namespace Progmasoft.Tazel.Project; + +/// <summary>What is wrong with a module, its project files or what they name.</summary> +public sealed class ProjectException : Exception +{ + /// <summary>A problem of the project.</summary> + public ProjectException(string message) + : base(message) + { + } + + /// <summary>Nothing to say.</summary> + public ProjectException() + { + } + + /// <summary>A problem and its cause.</summary> + public ProjectException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// <summary>Runs <c>MODULE.csx</c> and <c>BUILD.csx</c> files with the C# scripting of Roslyn.</summary> +internal static class ScriptHost +{ + /// <summary>The namespace every project file sees without a <c>using</c>.</summary> + public const string CommonNamespace = "Progmasoft.Tazel.Dsl.Common"; + + private static readonly ScriptOptions BaseOptions = CreateOptions(); + + /// <summary> + /// Compiles and runs <paramref name="code"/> with <paramref name="globals"/>; <paramref name="shownPath"/> names + /// the file in messages. A compile error or an exception of the script becomes a <see cref="ProjectException"/>. + /// </summary> + public static async Task RunAsync<TGlobals>(string code, string shownPath, TGlobals globals) + where TGlobals : class + { + var script = CSharpScript.Create(code, BaseOptions.WithFilePath(shownPath), typeof(TGlobals)); + var errors = script.Compile().Where(d => d.Severity == DiagnosticSeverity.Error).ToList(); + if (errors.Count > 0) + { + throw new ProjectException(Describe(errors, shownPath)); + } + + try + { + await script.RunAsync(globals).ConfigureAwait(false); + } + catch (DslException error) + { + throw new ProjectException(error.Message, error); + } + catch (CompilationErrorException error) + { + throw new ProjectException(Describe(error.Diagnostics, shownPath), error); + } + catch (Exception error) + { + throw new ProjectException($"{shownPath}: {Where(error, shownPath)}{error.GetType().Name}: {error.Message}", error); + } + } + + private static ScriptOptions CreateOptions() + { + var runtime = Path.GetDirectoryName(typeof(object).Assembly.Location)!; + var references = new List<MetadataReference>(); + foreach (var name in new[] { "System.Runtime.dll", "System.Collections.dll", "System.Linq.dll", "netstandard.dll" }) + { + var file = Path.Combine(runtime, name); + if (File.Exists(file)) + { + references.Add(MetadataReference.CreateFromFile(file)); + } + } + + foreach (var assembly in new[] { typeof(object).Assembly, typeof(Enumerable).Assembly, typeof(DslException).Assembly }) + { + references.Add(MetadataReference.CreateFromFile(assembly.Location)); + } + + return ScriptOptions.Default + .WithReferences(references) + .WithImports(CommonNamespace) + .WithLanguageVersion(LanguageVersion.Latest) + .WithOptimizationLevel(OptimizationLevel.Debug) + .WithEmitDebugInformation(false) + .WithAllowUnsafe(false) + .WithCheckOverflow(true); + } + + private static string Describe(IEnumerable<Diagnostic> diagnostics, string shownPath) + { + var text = new StringBuilder(); + foreach (var diagnostic in diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).Take(20)) + { + var span = diagnostic.Location.GetLineSpan(); + var position = span.StartLinePosition; + text.Append(shownPath).Append(':').Append(position.Line + 1).Append(':').Append(position.Character + 1) + .Append(": ").Append(diagnostic.Id).Append(": ") + .Append(diagnostic.GetMessage(System.Globalization.CultureInfo.InvariantCulture)).Append('\n'); + } + + return text.ToString().TrimEnd('\n'); + } + + // The line of the script an exception came from, when its stack trace has one. + private static string Where(Exception error, string shownPath) + { + var trace = new System.Diagnostics.StackTrace(error, fNeedFileInfo: true); + foreach (var frame in trace.GetFrames()) + { + if (frame.GetFileName() == shownPath && frame.GetFileLineNumber() > 0) + { + return $"{frame.GetFileLineNumber()}: "; + } + } + + return ""; + } + + /// <summary>Whether a type is from the DSL, for messages that name what a script returned.</summary> + public static bool IsDslType(Type type) => type.Assembly == typeof(DslException).Assembly; + + /// <summary>The assembly of the DSL, for diagnostics.</summary> + public static Assembly DslAssembly => typeof(DslException).Assembly; +} diff --git a/src/Progmasoft.Tazel/Project/TargetChecks.cs b/src/Progmasoft.Tazel/Project/TargetChecks.cs new file mode 100644 index 0000000..1d06ae9 --- /dev/null +++ b/src/Progmasoft.Tazel/Project/TargetChecks.cs @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Linq; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Dsl.Build.Prelude; + +namespace Progmasoft.Tazel.Project; + +/// <summary>Checks the settings of one target, apart from what it depends on.</summary> +internal static class TargetChecks +{ + public static void Check(ProjectTarget target) + { + var place = target.Place; + switch (target.Settings) + { + case ZigModuleSettings zig: + if (zig.RootSourceFile.Length == 0) + { + throw new ProjectException($"{place}: {target.Label} needs its RootSourceFile"); + } + + if (!zig.RootSourceFile.EndsWith(".zig", StringComparison.Ordinal)) + { + throw new ProjectException($"{place}: the RootSourceFile '{zig.RootSourceFile}' is not a .zig file"); + } + + foreach (var name in zig.ModuleImports.Keys) + { + if (name.Length == 0 || !name.All(c => char.IsAsciiLetterOrDigit(c) || c == '_')) + { + throw new ProjectException($"{place}: '{name}' cannot be the name of an @import"); + } + } + + break; + case CCSettings cc: + foreach (var option in cc.PreprocessorDefinitions.Concat(cc.LocalPreprocessorDefinitions)) + { + if (option.Length == 0 || option.StartsWith('-')) + { + throw new ProjectException($"{place}: '{option}' is not a macro; write NAME or NAME=value"); + } + } + + break; + } + + if (target.Settings is ITestSettings test) + { + if (test.ShardCount < 1) + { + throw new ProjectException($"{place}: ShardCount is at least 1"); + } + + if (test.Timeout is { } timeout && timeout <= TimeSpan.Zero) + { + throw new ProjectException($"{place}: Timeout must be longer than nothing"); + } + } + + if (target.Family == Family.Zig && target.Settings is not ZigModuleSettings) + { + throw new ProjectException($"{place}: {target.Label} has settings of another family"); + } + } +} diff --git a/src/Progmasoft.Tazel/Project/Workspace.cs b/src/Progmasoft.Tazel/Project/Workspace.cs new file mode 100644 index 0000000..2986964 --- /dev/null +++ b/src/Progmasoft.Tazel/Project/Workspace.cs @@ -0,0 +1,378 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using NuGet.Versioning; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Dsl.Module.Prelude; +using Progmasoft.Tazel.Label; + +namespace Progmasoft.Tazel.Project; + +/// <summary>What a module says about itself, checked.</summary> +internal sealed record ModuleInfo(string Group, string Name, NuGetVersion Version, ModuleDefinition Definition); + +/// <summary>A module whose MODULE.csx ran: the main one, or a dependency by the name its labels use.</summary> +internal sealed class LoadedModule(string root, string? repository, ModuleGlobals globals, ModuleInfo info) +{ + public string Root { get; } = root; + + public string? Repository { get; } = repository; + + public ModuleGlobals Globals { get; } = globals; + + public ModuleInfo Info { get; } = info; + + /// <summary>How messages name a file of this module.</summary> + public string Shown(string relative) => Repository is null ? relative : $"@{Repository}//{relative}"; +} + +/// <summary>A target, with what it depends on found.</summary> +internal sealed class ProjectTarget +{ + public required TargetLabel Label { get; init; } + + public required Family Family { get; init; } + + public required TargetKind Kind { get; init; } + + public required TargetSettings Settings { get; init; } + + /// <summary>Where it is declared, <c>file:line</c>.</summary> + public required string Place { get; init; } + + public required string PackageDirectory { get; init; } + + public required LoadedModule Module { get; init; } + + /// <summary>The platforms it builds for.</summary> + public required IReadOnlyList<Platform> Constraints { get; init; } + + public List<ProjectTarget> Dependencies { get; } = []; + + /// <summary>For Zig targets: the modules they import, by the name <c>@import</c> uses.</summary> + public Dictionary<string, ProjectTarget> ZigImports { get; } = new(StringComparer.Ordinal); + + public bool IsManual => Settings.Tags.Contains("manual", StringComparer.Ordinal); + + public bool IsLibrary => Kind is TargetKind.StaticLibrary or TargetKind.SharedLibrary; + + public bool IsRunnable => Kind is TargetKind.Executable or TargetKind.Test; + + public bool BuildsFor(Platform platform) => Constraints.Count == 0 || Constraints.Contains(platform); + + public override string ToString() => Label.ToString(); +} + +/// <summary>A toolchain a project file declared.</summary> +internal sealed record ProjectToolchain(TargetLabel Label, Family Family, object Settings, string Place); + +/// <summary>The modules of a command, their packages, targets and toolchains.</summary> +internal sealed class Workspace +{ + private Workspace(LoadedModule main) + { + Main = main; + } + + public LoadedModule Main { get; } + + public Dictionary<string, LoadedModule> External { get; } = new(StringComparer.Ordinal); + + public Dictionary<TargetLabel, ProjectTarget> Targets { get; } = []; + + public Dictionary<TargetLabel, ProjectToolchain> Toolchains { get; } = []; + + /// <summary>The packages of every module.</summary> + public List<PackageId> Packages { get; } = []; + + /// <summary>The toolchains the main module registers, in its order.</summary> + public List<ProjectToolchain> Registered { get; } = []; + + /// <summary>Loads the module that <paramref name="directory"/> is in, with the modules it depends on.</summary> + public static async Task<Workspace> LoadAsync(string directory, BuildContext build, Version tazelVersion) + { + var root = ModuleFiles.FindRoot(directory); + var main = await LoadModuleAsync(root, null, tazelVersion).ConfigureAwait(false); + var workspace = new Workspace(main); + await workspace.LoadDependenciesAsync(main, tazelVersion).ConfigureAwait(false); + await workspace.LoadPackagesAsync(main, build).ConfigureAwait(false); + foreach (var module in workspace.External.Values) + { + await workspace.LoadPackagesAsync(module, build).ConfigureAwait(false); + } + + workspace.Resolve(); + return workspace; + } + + /// <summary>Runs only the MODULE.csx of the module <paramref name="directory"/> is in.</summary> + public static Task<LoadedModule> LoadMainModuleAsync(string directory, Version tazelVersion) => + LoadModuleAsync(ModuleFiles.FindRoot(directory), null, tazelVersion); + + private static async Task<LoadedModule> LoadModuleAsync(string root, string? repository, Version tazelVersion) + { + var file = Path.Combine(root, ModuleFiles.ModuleFile); + var shown = repository is null ? ModuleFiles.ModuleFile : $"@{repository}//{ModuleFiles.ModuleFile}"; + var globals = new ModuleGlobals(); + await ScriptHost.RunAsync(await File.ReadAllTextAsync(file).ConfigureAwait(false), shown, globals) + .ConfigureAwait(false); + var definition = globals.module?.Definition + ?? throw new ProjectException($"{shown} sets no module: module = Module.Define(new() {{ ... }});"); + if (!Labels.IsName(definition.Name)) + { + throw new ProjectException($"{shown}: the module name '{definition.Name}' must be letters, digits and _ + . -"); + } + + if (!IsGroup(definition.Group)) + { + throw new ProjectException( + $"{shown}: the group '{definition.Group}' must be names joined by dots, such as com.example"); + } + + if (!NuGetVersion.TryParseStrict(definition.Version, out var version)) + { + throw new ProjectException($"{shown}: '{definition.Version}' is not a SemVer version such as 1.2.0"); + } + + if (definition.Compatibility is { } compatibility && !compatibility.Admits(tazelVersion)) + { + throw new ProjectException( + $"{shown} builds with Tazel {compatibility}; this is Tazel {tazelVersion.ToString(3)}"); + } + + return new LoadedModule(root, repository, globals, new ModuleInfo(definition.Group, definition.Name, version, definition)); + } + + private static bool IsGroup(string group) => + group.Length > 0 && group.Split('.').All(part => + part.Length > 0 && part.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-')); + + private async Task LoadDependenciesAsync(LoadedModule module, Version tazelVersion) + { + foreach (var dependency in module.Globals.dependencies?.Items ?? []) + { + if (dependency.Portal is { } portal) + { + throw new ProjectException( + $"{module.Shown(ModuleFiles.ModuleFile)}: {portal.Group}:{portal.Name}:{portal.Version} is a module of " + + "Tazel Portal Modules, and this Tazel fetches no modules; use LocalModule.From with its archive"); + } + + var local = dependency.Local!; + var place = module.Shown(ModuleFiles.ModuleFile); + if (!Labels.IsName(local.Name)) + { + throw new ProjectException($"{place}: the local module name '{local.Name}' must be letters, digits and _ + . -"); + } + + if (External.ContainsKey(local.Name)) + { + throw new ProjectException($"{place}: two dependencies are named '{local.Name}'"); + } + + var unpacked = LocalModules.Unpack(Main.Root, module.Root, local, place); + var loaded = await LoadModuleAsync(unpacked, local.Name, tazelVersion).ConfigureAwait(false); + External[local.Name] = loaded; + await LoadDependenciesAsync(loaded, tazelVersion).ConfigureAwait(false); + } + } + + private async Task LoadPackagesAsync(LoadedModule module, BuildContext build) + { + var packages = ModuleFiles.Packages(module.Root); + var scopes = await Task.WhenAll(packages.Select(package => Task.Run(async () => + { + var shown = module.Shown(FileSets.ToRoot(package.File, module.Root)); + var scope = new DeclarationScope(package.Path, shown); + var code = await File.ReadAllTextAsync(package.File).ConfigureAwait(false); + using (Declarations.Enter(scope)) + { + await ScriptHost.RunAsync(code, shown, new BuildGlobals(build)).ConfigureAwait(false); + } + + return (Package: package, Scope: scope); + }))).ConfigureAwait(false); + + foreach (var (package, scope) in scopes) + { + var id = new PackageId(module.Repository, package.Path); + Packages.Add(id); + var directory = Path.GetDirectoryName(package.File)!; + foreach (var declared in scope.Targets) + { + var label = new TargetLabel(id, declared.Name); + var settings = (TargetSettings)declared.Settings; + var constraints = settings.TargetConstraints.Count == 0 && declared.Family == Family.ObjectiveC + ? ObjectiveCDefaults.Platforms + : settings.TargetConstraints; + Targets[label] = new ProjectTarget + { + Label = label, + Family = declared.Family, + Kind = declared.Kind, + Settings = settings, + Place = $"{declared.File}:{declared.Line}", + PackageDirectory = directory, + Module = module, + Constraints = constraints, + }; + } + + foreach (var declared in scope.Toolchains) + { + var label = new TargetLabel(id, declared.Name); + Toolchains[label] = new ProjectToolchain(label, declared.Family, declared.Settings, $"{declared.File}:{declared.Line}"); + } + } + } + + private void Resolve() + { + foreach (var target in Targets.Values) + { + TargetChecks.Check(target); + foreach (var reference in target.Settings.Depends.Items) + { + var found = Find(reference.Label, target); + if (found.Kind is TargetKind.Executable or TargetKind.Test) + { + throw new ProjectException($"{target.Place}: {found.Label} is a {Describe(found)}; only libraries are linked"); + } + + if (found.Kind == TargetKind.Module) + { + throw new ProjectException($"{target.Place}: {found.Label} is a Zig module; name it in ModuleImports"); + } + + target.Dependencies.Add(found); + } + + if (target.Settings is ZigModuleSettings zig) + { + foreach (var (name, labelText) in zig.ModuleImports) + { + var found = Find(labelText, target); + if (found.Kind != TargetKind.Module) + { + throw new ProjectException($"{target.Place}: ModuleImports[\"{name}\"] names {found.Label}, which is not a Zig module"); + } + + target.ZigImports[name] = found; + } + } + } + + CheckCycles(); + foreach (var labelText in Main.Globals.toolchains?.Labels ?? []) + { + TargetLabel label; + try + { + label = Labels.Target(labelText, PackageId.Root); + } + catch (LabelException error) + { + throw new ProjectException($"{ModuleFiles.ModuleFile}: {error.Message}", error); + } + + Registered.Add(Toolchains.TryGetValue(label, out var toolchain) + ? toolchain + : throw new ProjectException($"{ModuleFiles.ModuleFile}: no toolchain {label} is declared")); + } + } + + private ProjectTarget Find(string text, ProjectTarget from) + { + TargetLabel label; + try + { + label = Labels.Target(text, from.Label.Package); + } + catch (LabelException error) + { + throw new ProjectException($"{from.Place}: {error.Message}", error); + } + + if (label.Package.Repository is null && from.Module.Repository is not null) + { + label = label with { Package = label.Package with { Repository = from.Module.Repository } }; + } + + if (!Targets.TryGetValue(label, out var found)) + { + var hint = Suggest(label); + throw new ProjectException($"{from.Place}: {from.Label} depends on {label}, which is not declared{hint}"); + } + + var visible = found.Settings.Visibility switch + { + Visibility.Public => true, + Visibility.Module => found.Module == from.Module, + _ => found.Label.Package == from.Label.Package, + }; + if (!visible) + { + throw new ProjectException( + $"{from.Place}: {found.Label} is {found.Settings.Visibility.ToString().ToLowerInvariant()}, " + + $"so {from.Label} may not depend on it; set Visibility on {found.Label}"); + } + + return found; + } + + private string Suggest(TargetLabel label) + { + var near = Targets.Keys.Where(k => k.Package == label.Package) + .Select(k => k.Name).OrderBy(n => Cli.Suggestions.Distance(n, label.Name)).FirstOrDefault(); + return near is not null && Cli.Suggestions.Distance(near, label.Name) <= 2 ? $"; did you mean :{near}?" : ""; + } + + private static string Describe(ProjectTarget target) => target.Kind switch + { + TargetKind.Executable => "executable", + TargetKind.Test => "test", + _ => target.Kind.ToString(), + }; + + private void CheckCycles() + { + var state = new Dictionary<ProjectTarget, int>(); + var path = new List<ProjectTarget>(); + foreach (var target in Targets.Values.OrderBy(t => t.Label.ToString(), StringComparer.Ordinal)) + { + Visit(target); + } + + void Visit(ProjectTarget target) + { + if (state.TryGetValue(target, out var seen)) + { + if (seen == 1) + { + var start = path.IndexOf(target); + var cycle = string.Join(" -> ", path.Skip(start).Append(target).Select(t => t.Label)); + throw new ProjectException($"{target.Place}: the targets depend on each other: {cycle}"); + } + + return; + } + + state[target] = 1; + path.Add(target); + foreach (var next in target.Dependencies.Concat(target.ZigImports.Values)) + { + Visit(next); + } + + path.RemoveAt(path.Count - 1); + state[target] = 2; + } + } +} diff --git a/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs b/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs new file mode 100644 index 0000000..8122959 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs @@ -0,0 +1,182 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Threading.Tasks; +using Progmasoft.Tazel.Driver; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +/// <summary>Whole commands on a real compiler; skipped where none is on PATH.</summary> +public sealed class BuildCommandTests +{ + private const string Build = """ + using Progmasoft.Tazel.Dsl.Build.Prelude; + var math = CC.StaticLibrary("math", new() + { + Sources = ["math.cpp"], + Headers = ["math.hpp"], + Visibility = Visibility.Module, + }); + CC.Executable("app", new() + { + Sources = ["main.cpp", "half.c"], + Depends = [math], + CCompilerOptions = ["-DONLY_C"], + CppCompilerOptions = ["-DONLY_CXX"], + RuntimeData = ["data.txt"], + }); + CC.Test("math_test", new() { Sources = ["math_test.cpp"], Depends = [math], ShardCount = 2 }); + CC.Test("failing", new() { Sources = ["failing.cpp"], Tags = ["manual"] }); + """; + + private static TemporaryModule Sample() => new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("BUILD.csx", Build) + .Write("math.hpp", "int add(int a, int b);\n") + .Write("math.cpp", "#include \"math.hpp\"\nint add(int a, int b) { return a + b; }\n") + .Write("half.c", "#ifdef ONLY_CXX\n#error C++ options reached C\n#endif\nint half(int x) { return x / 2; }\n") + .Write("main.cpp", """ + #include <cstdio> + #include "math.hpp" + #ifdef ONLY_C + #error C options reached C++ + #endif + extern "C" int half(int); + int main() { + std::FILE* f = std::fopen("data.txt", "r"); + return f != nullptr && add(half(40), 1) == 21 ? 0 : 1; + } + """) + .Write("data.txt", "data\n") + .Write("math_test.cpp", "#include \"math.hpp\"\nint main() { return add(2, 2) == 4 ? 0 : 1; }\n") + .Write("failing.cpp", "int main() { return 3; }\n"); + + [Fact] + public async Task BuildsRunsAndTestsAModule() + { + Assert.SkipWhen(Host.Which("clang++") is null && Host.Which("g++") is null, "no C++ compiler on PATH"); + using var module = Sample(); + var (status, output) = await module.TazelAsync(".", "build", "//..."); + Assert.True(status == 0, output); + Assert.Contains("Compiling //:app half.c", output, StringComparison.Ordinal); + + // Nothing changed, so nothing runs again. + (status, output) = await module.TazelAsync(".", "build", "//..."); + Assert.True(status == 0, output); + Assert.DoesNotContain("Compiling", output, StringComparison.Ordinal); + + (status, output) = await module.TazelAsync(".", "run", "//:app"); + Assert.True(status == 0, output); + + (status, output) = await module.TazelAsync(".", "test", "//..."); + Assert.True(status == 0, output); + Assert.Contains("//:math_test", output, StringComparison.Ordinal); + Assert.DoesNotContain("//:failing", output, StringComparison.Ordinal); + Assert.True(File.Exists(Path.Combine(module.Root, ".tazel", "testlogs", "math_test", "test.log"))); + + (status, output) = await module.TazelAsync(".", "test", "//:failing"); + Assert.Equal(1, status); + Assert.Contains("FAILED", output, StringComparison.Ordinal); + } + + [Fact] + public async Task ACompilerErrorStopsTheBuildWithItsCommand() + { + Assert.SkipWhen(Host.Which("clang++") is null && Host.Which("g++") is null, "no C++ compiler on PATH"); + using var module = Sample(); + module.Write("math.cpp", "this is not C++\n"); + var (status, output) = await module.TazelAsync(".", "build", "//:app"); + Assert.Equal(1, status); + Assert.Contains("FAILED Compiling //:math math.cpp", output, StringComparison.Ordinal); + Assert.Contains("-c math.cpp", output, StringComparison.Ordinal); + } + + [Fact] + public async Task ASandboxAskedForStopsTheBuild() + { + using var module = Sample(); + module.Write("tazel_options.txt", "sandboxing-with-microvm: true;"); + var (status, output) = await module.TazelAsync(".", "build", "//..."); + Assert.Equal(1, status); + Assert.Contains("this Tazel has no MicroVM to start, so nothing ran", output, StringComparison.Ordinal); + } + + [Fact] + public async Task BuildsAZigProgramThatImportsAModule() + { + Assert.SkipWhen(Host.Which("zig") is null, "no zig on PATH"); + using var module = new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("BUILD.csx", """ + using System.Collections.Generic; + using Progmasoft.Tazel.Dsl.Build.Prelude; + Zig.Module("core", new() { RootSourceFile = "core.zig" }); + Zig.Executable("app", new() + { + RootSourceFile = "main.zig", + ModuleImports = new Dictionary<string, string> { ["core"] = ":core" }, + }); + Zig.Test("core_test", new() { RootSourceFile = "core.zig" }); + """) + .Write("core.zig", "const std = @import(\"std\");\npub fn add(a: i32, b: i32) i32 { return a + b; }\ntest \"add\" { try std.testing.expect(add(1, 2) == 3); }\n") + .Write("main.zig", "const core = @import(\"core\");\npub fn main() !void { if (core.add(1, 2) != 3) return error.Wrong; }\n"); + var (status, output) = await module.TazelAsync(".", "test", "//..."); + Assert.True(status == 0, output); + (status, output) = await module.TazelAsync(".", "run", "//:app"); + Assert.True(status == 0, output); + } + + [Fact] + public async Task PackagesTheModuleReproducibly() + { + using var module = Sample(); + var (status, output) = await module.TazelAsync(".", "package"); + Assert.True(status == 0, output); + var archive = Path.Combine(module.Root, ".tazel", "package", "com.example.sample-0.1.0.tazel.tar.xz"); + var first = Archive.Sha256Sums.Sha256(archive); + Assert.Equal($"{first} com.example.sample-0.1.0.tazel.tar.xz\n", await File.ReadAllTextAsync(archive + ".sha256sums", TestContext.Current.CancellationToken)); + (status, _) = await module.TazelAsync(".", "package"); + Assert.Equal(0, status); + Assert.Equal(first, Archive.Sha256Sums.Sha256(archive)); + } + + [Fact] + public async Task ADependencyComesFromItsArchive() + { + using var library = new TemporaryModule() + .Write("MODULE.csx", """ + using Progmasoft.Tazel.Dsl.Module.Prelude; + module = Module.Define(new() { Group = "com.example", Name = "lib", Version = "1.0.0" }); + """) + .Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.StaticLibrary(\"lib\", new() { Visibility = Visibility.Public });\nCC.StaticLibrary(\"hidden\", new() { Visibility = Visibility.Module });"); + var (status, output) = await library.TazelAsync(".", "package"); + Assert.True(status == 0, output); + var archive = Path.Combine(library.Root, ".tazel", "package", "com.example.lib-1.0.0.tazel.tar.xz"); + var sha = Archive.Sha256Sums.Sha256(archive); + + using var app = new TemporaryModule(); + Directory.CreateDirectory(Path.Combine(app.Root, "deps")); + File.Copy(archive, Path.Combine(app.Root, "deps", "lib.tazel.tar.xz")); + app.Write("MODULE.csx", TemporaryModule.ModuleFile + $$""" + + dependencies = Dependencies.Define(LocalModule.From(new() { Name = "lib", Include = "deps/lib.tazel.tar.xz", Sha256 = "{{sha}}" })); + """) + .Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.StaticLibrary(\"app\", new() { Depends = [\"@lib//:lib\"] });"); + var workspace = await app.LoadAsync(); + Assert.Contains(workspace.Targets.Keys, label => label.ToString() == "@lib//:lib"); + + app.Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.StaticLibrary(\"app\", new() { Depends = [\"@lib//:hidden\"] });"); + var error = await Assert.ThrowsAsync<Project.ProjectException>(() => app.LoadAsync()); + Assert.Contains("@lib//:hidden is module", error.Message, StringComparison.Ordinal); + + app.Write("MODULE.csx", TemporaryModule.ModuleFile + """ + + dependencies = Dependencies.Define(LocalModule.From(new() { Name = "lib", Include = "deps/lib.tazel.tar.xz", Sha256 = "0000000000000000000000000000000000000000000000000000000000000000" })); + """); + error = await Assert.ThrowsAsync<Project.ProjectException>(() => app.LoadAsync()); + Assert.Contains("has the SHA-256", error.Message, StringComparison.Ordinal); + } +} diff --git a/tests/Progmasoft.Tazel.Tests/CommandLineTests.cs b/tests/Progmasoft.Tazel.Tests/CommandLineTests.cs new file mode 100644 index 0000000..f17df6d --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/CommandLineTests.cs @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Output; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class CommandLineTests +{ + [Theory] + [InlineData("--platform", "macos-arm64")] + [InlineData("--platform=macos-arm64")] + [InlineData("--platform:macos-arm64")] + public void ALongOptionTakesItsValueAfterSpaceEqualsOrColon(params string[] option) + { + var build = Assert.IsType<BuildCommand>(CommandLine.Parse(["build", .. option, "//..."])); + Assert.Equal(Platform.MacOSArm64, build.Flags.Platform); + Assert.Equal(["//..."], build.Labels); + } + + [Fact] + public void AListGoesAfterEqualsOrColonAndRepeatsKeepTheirOrder() + { + var build = Assert.IsType<BuildCommand>(CommandLine.Parse( + ["build", "--compiler-options=-O2,-g", "--compiler-options", "-Wall", "--linker-options:-Wl\\,--as-needed"])); + Assert.Equal(["-O2", "-g", "-Wall"], build.Flags.CompilerOptions); + Assert.Equal(["-Wl,--as-needed"], build.Flags.LinkerOptions); + } + + [Fact] + public void AValueAfterWhitespaceIsOneValue() + { + var build = Assert.IsType<BuildCommand>(CommandLine.Parse(["build", "--linker-options", "-Wl,--as-needed"])); + Assert.Equal(["-Wl,--as-needed"], build.Flags.LinkerOptions); + } + + [Fact] + public void OptionsMayStandAnywhereBeforeTheDashes() + { + var run = Assert.IsType<RunCommand>(CommandLine.Parse( + ["--quiet", "run", "//:x", "--mode", "release", "--", "--mode", "y"])); + Assert.Equal("//:x", run.Label); + Assert.Equal(BuildMode.Release, run.Flags.Mode); + Assert.Equal(["--mode", "y"], run.Arguments); + Assert.True(run.Output.Quiet); + } + + [Fact] + public void CustomTakesEverythingAfterIt() + { + var custom = Assert.IsType<CustomCommandLine>(CommandLine.Parse(["--color", "never", "custom", "build", "with", "-e", "--x"])); + Assert.Equal(["build", "with", "-e", "--x"], custom.Words); + Assert.Equal(When.Never, custom.Output.Color); + } + + [Theory] + [InlineData("--color:awlyas", "did you mean --color:always?")] + [InlineData("--color=nevr", "did you mean --color=never?")] + [InlineData("--featur=lto", "did you mean --feature=lto?")] + [InlineData("--expunge", "--expunge is not an option of tazel build")] + [InlineData("--jobs=0", "--jobs takes a number from 1 to 4096")] + [InlineData("-x", "-x is not an option")] + [InlineData("--keep-going=yes", "--keep-going takes no value")] + public void HintsKeepTheSpellingThatWasWritten(string option, string message) + { + var error = Assert.Throws<CommandLineException>(() => CommandLine.Parse(["build", option])); + Assert.Contains(message, error.Message, StringComparison.Ordinal); + } + + [Fact] + public void AMisspeltCommandGetsAHint() + { + var error = Assert.Throws<CommandLineException>(() => CommandLine.Parse(["biuld"])); + Assert.Contains("did you mean tazel build?", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void RunTakesOneTarget() + { + var error = Assert.Throws<CommandLineException>(() => CommandLine.Parse(["run", "//:a", "//:b"])); + Assert.Contains("the program's own arguments go after --", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void HelpComesFromNothingOrTheHelpOption() + { + Assert.IsType<HelpCommand>(CommandLine.Parse([])); + Assert.Equal("test", Assert.IsType<HelpCommand>(CommandLine.Parse(["test", "-h"])).Topic); + Assert.Equal("build", Assert.IsType<HelpCommand>(CommandLine.Parse(["help", "build"])).Topic); + } + + [Fact] + public void EveryCommandHasHelp() + { + foreach (var command in CommandLine.Commands) + { + Assert.NotEmpty(Help.Text(command)); + } + } + + [Theory] + [InlineData("a,b", new[] { "a", "b" })] + [InlineData("a\\,b", new[] { "a,b" })] + [InlineData("-Wl\\,-rpath\\,x,-g", new[] { "-Wl,-rpath,x", "-g" })] + public void SplitsListsAtCommasThatAreNotEscaped(string text, string[] items) => + Assert.Equal(items, CommandLine.SplitList(text)); + + [Fact] + public void TheDistanceCountsSwapsOnce() + { + Assert.Equal(1, Suggestions.Distance("biuld", "build")); + Assert.Equal(0, Suggestions.Distance("x", "x")); + Assert.Null(Suggestions.Nearest("zzz", ["build", "test"])); + } +} diff --git a/tests/Progmasoft.Tazel.Tests/FileTests.cs b/tests/Progmasoft.Tazel.Tests/FileTests.cs new file mode 100644 index 0000000..9b520e6 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/FileTests.cs @@ -0,0 +1,154 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Linq; +using CsCheck; +using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Project; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class GlobTests +{ + [Theory] + [InlineData("src/*.cpp", "src/a.cpp", true)] + [InlineData("src/*.cpp", "src/x/a.cpp", false)] + [InlineData("src/**/*.cpp", "src/a.cpp", true)] + [InlineData("src/**/*.cpp", "src/x/y/a.cpp", true)] + [InlineData("**", "a/b/c", true)] + [InlineData("a?.c", "ab.c", true)] + [InlineData("a?.c", "a.c", false)] + [InlineData("include/**", "include", true)] + public void MatchesAsBazelGlobsDo(string pattern, string path, bool matches) => + Assert.Equal(matches, FileSets.Matches(pattern, path)); + + [Fact] + public void APathWithoutWildcardsMatchesOnlyItself() => + Gen.String[Gen.Char['a', 'z'], 1, 8].Array[1, 4].Sample(parts => + { + var path = string.Join('/', parts); + Assert.True(FileSets.Matches(path, path)); + Assert.True(FileSets.Matches("**", path)); + Assert.False(FileSets.Matches(path + "x", path)); + }); + + [Fact] + public void AGlobLeavesOutSubpackagesHiddenFilesAndWhatItExcludes() + { + using var module = new TemporaryModule(); + module.Write("src/a.c", "").Write("src/b.c", "").Write("src/.hidden.c", "").Write("src/sub/c.c", "") + .Write("src/sub2/BUILD.csx", "").Write("src/sub2/d.c", ""); + var files = FileSets.Resolve(new Glob("src/**/*.c", ["src/b.c"]), module.Root, module.Root, "BUILD.csx:1"); + Assert.Equal(["src/a.c", "src/sub/c.c"], files); + } + + [Theory] + [InlineData("../x.c")] + [InlineData("/etc/passwd")] + [InlineData("a//b.c")] + public void APathMustStayBelowItsProjectFile(string path) + { + using var module = new TemporaryModule(); + Assert.Throws<ProjectException>(() => + FileSets.Resolve([path], module.Root, module.Root, "BUILD.csx:1")); + } +} + +public sealed class DepfileTests +{ + [Fact] + public void ReadsTheInputsOfADepfile() + { + var inputs = Depfiles.Inputs("out/a.o: src/a.c \\\n include/a\\ b.h \\\r\n x$$y.h\n"); + Assert.Equal(["src/a.c", "include/a b.h", "x$y.h"], inputs); + } + + [Fact] + public void ADepfileWithoutAColonHasNoInputs() => Assert.Empty(Depfiles.Inputs("nothing")); +} + +public sealed class ArchiveTests +{ + [Fact] + public void AnArchiveIsTheSameWhenWrittenTwice() + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", TemporaryModule.ModuleFile).Write("BUILD.csx", "").Write("src/a.c", "int a;") + .Write(".git/HEAD", "x").Write("docs/x.md", "x"); + var files = ModuleArchive.Files(module.Root, relative => relative.StartsWith("docs/", StringComparison.Ordinal)); + Assert.Equal(["BUILD.csx", "MODULE.csx", "src/a.c"], files); + var first = Path.Combine(module.Root, "out", "one" + ModuleArchive.Extension); + var second = Path.Combine(module.Root, "out", "two" + ModuleArchive.Extension); + ModuleArchive.Write(module.Root, "com.example.sample-0.1.0", first, files); + File.SetLastWriteTimeUtc(Path.Combine(module.Root, "src/a.c"), DateTime.UtcNow.AddDays(-3)); + ModuleArchive.Write(module.Root, "com.example.sample-0.1.0", second, files); + Assert.Equal(Sha256Sums.Sha256(first), Sha256Sums.Sha256(second)); + + var unpacked = ModuleArchive.Unpack(first, Path.Combine(module.Root, "unpacked")); + Assert.Equal("int a;", File.ReadAllText(Path.Combine(unpacked, "src/a.c"))); + Assert.Equal("com.example.sample-0.1.0", Path.GetFileName(unpacked)); + } + + [Fact] + public void ReadsTheLinesOfSha256Sums() + { + var sum = new string('a', 64); + Assert.Equal(sum, Sha256Sums.SumFor($"{sum} x.tazel.tar.xz\n\n{new string('b', 64)} *y\n", "x.tazel.tar.xz", "s")); + Assert.Null(Sha256Sums.SumFor($"{sum} other\n", "x", "s")); + Assert.Throws<ProjectException>(() => Sha256Sums.SumFor("not a line\n", "x", "s")); + Assert.Throws<ProjectException>(() => Sha256Sums.SumFor($"{sum} x\n{sum} x\n", "x", "s")); + } +} + +public sealed class ActionCacheTests +{ + [Fact] + public void AnActionIsCurrentWhileItsFilesKeepTheirContent() + { + using var module = new TemporaryModule(); + module.Write("in.txt", "one").Write("out.txt", "made"); + var action = new BuildAction + { + Description = "copy", + Command = ["cp", "in.txt", "out.txt"], + Directory = module.Root, + Inputs = ["in.txt"], + Outputs = ["out.txt"], + }; + var cache = new ActionCache(new Digests()); + Assert.False(cache.IsCurrent(action)); + cache.Record(action); + Assert.True(cache.IsCurrent(action)); + + // Touching a file changes nothing; changing what it holds does. + File.SetLastWriteTimeUtc(Path.Combine(module.Root, "in.txt"), DateTime.UtcNow.AddMinutes(-5)); + Assert.True(new ActionCache(new Digests()).IsCurrent(action)); + module.Write("in.txt", "two"); + Assert.False(new ActionCache(new Digests()).IsCurrent(action)); + + var other = new BuildAction + { + Description = "copy", + Command = ["cp", "-p", "in.txt", "out.txt"], + Directory = module.Root, + Inputs = ["in.txt"], + Outputs = ["out.txt"], + }; + cache.Record(action); + Assert.False(cache.IsCurrent(other)); + Assert.NotEqual(action.Key, other.Key); + Assert.Equal(action.Key, new BuildAction + { + Description = "another description", + Command = ["cp", "in.txt", "out.txt"], + Directory = module.Root, + Inputs = [], + Outputs = ["x"], + }.Key); + } +} diff --git a/tests/Progmasoft.Tazel.Tests/LabelTests.cs b/tests/Progmasoft.Tazel.Tests/LabelTests.cs new file mode 100644 index 0000000..51da8cd --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/LabelTests.cs @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using Progmasoft.Tazel.Label; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class LabelTests +{ + private static readonly PackageId App = new(null, "app"); + + [Theory] + [InlineData("//:x", null, "", "x")] + [InlineData("//app:greeter", null, "app", "greeter")] + [InlineData("//app/cli:main-1.0", null, "app/cli", "main-1.0")] + [InlineData(":local", null, "app", "local")] + [InlineData("@dep//:x", "dep", "", "x")] + [InlineData("@dep-2//lib:y", "dep-2", "lib", "y")] + public void ReadsTheFormsOfATargetLabel(string text, string? repository, string path, string name) + { + var label = Labels.Target(text, App); + Assert.Equal(new TargetLabel(new PackageId(repository, path), name), label); + } + + [Theory] + [InlineData("//...", null, "")] + [InlineData("//app/...", null, "app")] + [InlineData("@dep//...", "dep", "")] + public void ReadsPackagePatterns(string text, string? repository, string path) + { + var selection = Labels.Selection(text, PackageId.Root); + Assert.Equal(new PackagePattern(new PackageId(repository, path)), selection); + } + + [Theory] + [InlineData("//app", "names no target")] + [InlineData("//app/:x", "no / before the colon")] + [InlineData("app:x", "is not a label")] + [InlineData("//a/../b:x", "no . or .. parts")] + [InlineData("//:bad name", "must be letters")] + [InlineData("@dep:x", "has no //")] + public void RefusesWhatIsNotALabel(string text, string reason) + { + var error = Assert.Throws<LabelException>(() => Labels.Selection(text, PackageId.Root)); + Assert.Contains(reason, error.Message, System.StringComparison.Ordinal); + } + + [Fact] + public void APatternIsNotOneTarget() => + Assert.Throws<LabelException>(() => Labels.Target("//...", PackageId.Root)); + + [Fact] + public void APatternCoversItsPackageAndThoseBelow() + { + var pattern = new PackagePattern(new PackageId(null, "app")); + Assert.True(pattern.Covers(new PackageId(null, "app"))); + Assert.True(pattern.Covers(new PackageId(null, "app/cli"))); + Assert.False(pattern.Covers(new PackageId(null, "application"))); + Assert.False(pattern.Covers(new PackageId("dep", "app"))); + Assert.True(new PackagePattern(PackageId.Root).Covers(new PackageId(null, "x/y"))); + } + + [Fact] + public void LabelsPrintAsTheyAreWritten() + { + Assert.Equal("//app:greeter", Labels.Target("//app:greeter", PackageId.Root).ToString()); + Assert.Equal("@dep//:x", Labels.Target("@dep//:x", PackageId.Root).ToString()); + Assert.Equal("//app/...", Labels.Selection("//app/...", PackageId.Root).ToString()); + Assert.Equal("//...", Labels.Selection("//...", PackageId.Root).ToString()); + } +} diff --git a/tests/Progmasoft.Tazel.Tests/PlannerTests.cs b/tests/Progmasoft.Tazel.Tests/PlannerTests.cs new file mode 100644 index 0000000..1a94b8b --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/PlannerTests.cs @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Label; +using Progmasoft.Tazel.Project; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +/// <summary>The command lines a build makes, for a toolchain of files that are never run, so they are the same everywhere.</summary> +public sealed class PlannerTests +{ + private static string ModuleWithToolchain(string root) => TemporaryModule.ModuleFile + """ + + toolchains = Toolchains.Define("//toolchains:fake"); + """; + + private static string Toolchain(string root) => $$""" + using Progmasoft.Tazel.Dsl.Build.Toolchain.Prelude; + var warnings = CC.Feature("warnings", new() + { + Enabled = true, + FlagSets = [ new() { Actions = [CCAction.CCompile, CCAction.CppCompile], Flags = ["-Wall"] } ] + }); + var lto = CC.Feature("lto", new() + { + FlagSets = [ new() { Actions = [CCAction.CppCompile, CCAction.CppLinkSharedLibrary], Flags = ["-flto"] } ] + }); + CC.Toolchain("fake", new() + { + ExecutionPlatform = Platform.{{Host.Platform}}, + TargetPlatform = Platform.LinuxAmd64, + Tools = new() + { + CCompiler = @"{{Path.Combine(root, "tools", "cc")}}", + CppCompiler = @"{{Path.Combine(root, "tools", "c++")}}", + Archiver = @"{{Path.Combine(root, "tools", "ar")}}", + }, + Features = [warnings, lto], + }); + Zig.Toolchain("zig", new() + { + ExecutionPlatform = Platform.{{Host.Platform}}, + TargetPlatform = Platform.LinuxAmd64, + Tools = new() { Zig = @"{{Path.Combine(root, "tools", "zig")}}" }, + }); + """; + + private const string Build = """ + using System; + using System.Collections.Generic; + using Progmasoft.Tazel.Dsl.Build.Prelude; + var math = CC.StaticLibrary("math", new() + { + Sources = new Glob("src/*.cpp"), + Headers = ["include/math.hpp"], + IncludeDirectories = ["include"], + CppCompilerOptions = ["-std=c++23"], + PreprocessorDefinitions = ["MATH_API=1"], + LocalPreprocessorDefinitions = ["MATH_BUILD=1"], + LinkerOptions = ["-lm"], + AlwaysLink = true, + }); + CC.SharedLibrary("shared", new() + { + Sources = ["src/shared.c"], + Depends = [math], + CCompilerOptions = ["-std=c17"], + LibraryVersion = new Version(1, 2, 0), + Features = [CC.Enable("lto"), CC.Disable("warnings")], + }); + CC.Executable("app", new() + { + Sources = ["src/main.cc"], + Depends = [":shared", math], + LinkingMode = LinkingMode.PreferStatic, + }); + Zig.Module("core", new() { RootSourceFile = "zig/core.zig" }); + Zig.Executable("zapp", new() + { + RootSourceFile = "zig/main.zig", + ModuleImports = new Dictionary<string, string> { ["core"] = ":core" }, + Depends = [math], + CSources = ["zig/shim.c"], + CCompilerOptions = ["-std=c17"], + LinkCStandardLibrary = true, + }); + """; + + [Fact] + public async Task TheCommandsOfABuild() + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", ModuleWithToolchain(module.Root)) + .Write("toolchains/BUILD.csx", Toolchain(module.Root)) + .Write("BUILD.csx", Build) + .Write("src/a.cpp", "").Write("src/b.cpp", "").Write("src/shared.c", "").Write("src/main.cc", "") + .Write("include/math.hpp", "").Write("zig/core.zig", "").Write("zig/main.zig", "").Write("zig/shim.c", "") + .Write("tools/cc", "").Write("tools/c++", "").Write("tools/ar", "").Write("tools/zig", ""); + var workspace = await Workspace.LoadAsync(module.Root, new BuildContext(BuildMode.Debug, Platform.LinuxAmd64), + new Version(0, 1, 0)); + var options = new BuildOptions + { + Platform = Platform.LinuxAmd64, + FeaturesOff = [], + CompilerOptions = ["-DFROM_COMMAND_LINE"], + LinkerOptions = ["-Wl,--as-needed"], + }; + var planner = new Planner(workspace, options, new ToolchainChooser(workspace, Platform.LinuxAmd64)); + var actions = new List<BuildAction>(); + foreach (var name in new[] { "app", "zapp" }) + { + Collect(planner.Plan(workspace.Targets[new TargetLabel(PackageId.Root, name)]).Main!, actions); + } + + // The program is left out: it is a path of this machine. Each argument is one line of the snapshot. + string Shown(string text) => text.Replace(module.Root, "{root}", StringComparison.Ordinal); + Snapshots.Match(actions.Select(action => new + { + action.Description, + Arguments = action.Command.Skip(1).Select(Shown).ToList(), + Inputs = action.Inputs.Select(Shown).ToList(), + Outputs = action.Outputs.Select(Shown).ToList(), + }).ToList()); + } + + [Fact] + public async Task AFeatureATargetNamesMustBeInItsToolchain() + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", ModuleWithToolchain(module.Root)) + .Write("toolchains/BUILD.csx", Toolchain(module.Root)) + .Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.StaticLibrary(\"x\", new() { Features = [CC.Enable(\"asan\")] });") + .Write("tools/cc", "").Write("tools/c++", "").Write("tools/ar", "").Write("tools/zig", ""); + var workspace = await Workspace.LoadAsync(module.Root, new BuildContext(BuildMode.Debug, Platform.LinuxAmd64), + new Version(0, 1, 0)); + var planner = new Planner(workspace, new BuildOptions { Platform = Platform.LinuxAmd64 }, + new ToolchainChooser(workspace, Platform.LinuxAmd64)); + var error = Assert.Throws<ProjectException>(() => planner.Plan(workspace.Targets.Values.Single())); + Assert.Contains("has no feature 'asan'", error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task AnotherPlatformNeedsARegisteredToolchain() + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.StaticLibrary(\"x\", new());"); + var other = Host.Platform == Platform.WindowsArm64 ? Platform.LinuxAmd64 : Platform.WindowsArm64; + var workspace = await Workspace.LoadAsync(module.Root, new BuildContext(BuildMode.Debug, other), new Version(0, 1, 0)); + var planner = new Planner(workspace, new BuildOptions { Platform = other }, new ToolchainChooser(workspace, other)); + var error = Assert.Throws<ProjectException>(() => planner.Plan(workspace.Targets.Values.Single())); + Assert.Contains($"builds for {other.Name()}", error.Message, StringComparison.Ordinal); + } + + private static void Collect(BuildAction action, List<BuildAction> into) + { + if (into.Contains(action)) + { + return; + } + + foreach (var prerequisite in action.Prerequisites) + { + Collect(prerequisite, into); + } + + into.Add(action); + } +} diff --git a/tests/Progmasoft.Tazel.Tests/Progmasoft.Tazel.Tests.csproj b/tests/Progmasoft.Tazel.Tests/Progmasoft.Tazel.Tests.csproj new file mode 100644 index 0000000..c36fa03 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/Progmasoft.Tazel.Tests.csproj @@ -0,0 +1,20 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <OutputType>Exe</OutputType> + <IsTestProject>true</IsTestProject> + <!-- Tests are not an API; their names say what they check. --> + <GenerateDocumentationFile>false</GenerateDocumentationFile> + </PropertyGroup> + <ItemGroup> + <ProjectReference Include="../../src/Progmasoft.Tazel/Progmasoft.Tazel.csproj" /> + <ProjectReference Include="../../src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="xunit.v3" /> + <PackageReference Include="CsCheck" /> + <PackageReference Include="Snapshooter.Xunit3" /> + <PackageReference Include="coverlet.MTP" /> + </ItemGroup> +</Project> diff --git a/tests/Progmasoft.Tazel.Tests/SnapshotTests.cs b/tests/Progmasoft.Tazel.Tests/SnapshotTests.cs new file mode 100644 index 0000000..15c1855 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/SnapshotTests.cs @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class SnapshotTests +{ + [Fact] + public void ADifferenceShowsTheLinesThatDifferWithTheirNeighbours() + { + using var module = new TemporaryModule(); + var lines = string.Join('\n', Array.ConvertAll(new int[20], _ => "same")); + module.Write("stored.snap", $"first\n{lines}\nold line\nlast\n").Write("new.snap", $"first\n{lines}\nnew line\nlast\n"); + var message = Snapshots.Describe(Path.Combine(module.Root, "stored.snap"), Path.Combine(module.Root, "new.snap")); + Assert.Contains("- old line\n+ new line\n", message, StringComparison.Ordinal); + Assert.Contains(" same\n same\n- old line", message, StringComparison.Ordinal); + Assert.Contains("+ new line\n last\n", message, StringComparison.Ordinal); + Assert.DoesNotContain("first", message, StringComparison.Ordinal); + Assert.Contains("new.snap. When it is right, move it over the stored one", message, StringComparison.Ordinal); + } + + [Fact] + public void AnAddedLineIsShownAlone() + { + using var module = new TemporaryModule(); + module.Write("stored.snap", "a\nb\n").Write("new.snap", "a\nadded\nb\n"); + var message = Snapshots.Describe(Path.Combine(module.Root, "stored.snap"), Path.Combine(module.Root, "new.snap")); + Assert.Contains(" a\n+ added\n b\n", message, StringComparison.Ordinal); + Assert.DoesNotContain("- a\n", message, StringComparison.Ordinal); + Assert.DoesNotContain("- b\n", message, StringComparison.Ordinal); + } +} diff --git a/tests/Progmasoft.Tazel.Tests/Snapshots.cs b/tests/Progmasoft.Tazel.Tests/Snapshots.cs new file mode 100644 index 0000000..5bdbf92 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/Snapshots.cs @@ -0,0 +1,155 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using Snapshooter; +using Snapshooter.Xunit3; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +/// <summary> +/// Snapshots with Snapshooter, in <c>__snapshots__/</c> beside the test. A difference fails with the lines that differ +/// and where the new snapshot is; a missing snapshot fails under <c>SNAPSHOOTER_STRICT_MODE=true</c>, as in CI, and +/// is written otherwise, for a review before it is committed. +/// </summary> +internal static class Snapshots +{ + private const int ContextLines = 2; + private const int MaxShownDifferences = 40; + + /// <summary>Compares <paramref name="value"/> with the snapshot of the calling test.</summary> + public static void Match(object value, [CallerFilePath] string source = "", [CallerMemberName] string test = "") + { + var folder = Path.Combine(Path.GetDirectoryName(source)!, "__snapshots__"); + var file = $"{Path.GetFileNameWithoutExtension(source)}.{test}.snap"; + var stored = Path.Combine(folder, file); + var mismatch = Path.Combine(folder, "__mismatch__", file); + var strict = string.Equals(Environment.GetEnvironmentVariable("SNAPSHOOTER_STRICT_MODE"), "true", + StringComparison.OrdinalIgnoreCase); + if (strict && !File.Exists(stored)) + { + Assert.Fail( + $"There is no snapshot {Shown(stored)}, and SNAPSHOOTER_STRICT_MODE=true does not let a test write one.\n" + + "Run the test once without SNAPSHOOTER_STRICT_MODE, read the snapshot it writes, and commit it."); + } + + // A mismatch of an earlier run says nothing about this one. + if (File.Exists(mismatch)) + { + File.Delete(mismatch); + } + try + { + // Snapshooter puts __snapshots__ below the folder it is given. + Snapshot.Match(value, new SnapshotFullName(file, Path.GetDirectoryName(source)!)); + } + catch (Exception) when (File.Exists(mismatch) && File.Exists(stored)) + { + Assert.Fail(Describe(stored, mismatch)); + } + } + + /// <summary>The lines that differ between the stored snapshot and the new one, with a few lines around each.</summary> + internal static string Describe(string stored, string mismatch) + { + var expected = File.ReadAllText(stored).ReplaceLineEndings("\n").Split('\n'); + var actual = File.ReadAllText(mismatch).ReplaceLineEndings("\n").Split('\n'); + var text = new StringBuilder() + .Append(CultureInfoInvariant($"The snapshot {Shown(stored)} differs from what the test made.\n")) + .Append("- is the stored snapshot, + is what the test made:\n\n"); + var shown = 0; + foreach (var (start, end) in Hunks(Diff(expected, actual))) + { + foreach (var (kind, line) in Diff(expected, actual).Skip(start).Take(end - start)) + { + text.Append(kind).Append(' ').Append(line).Append('\n'); + } + + text.Append("...\n"); + if (++shown == MaxShownDifferences) + { + break; + } + } + + return text + .Append(CultureInfoInvariant($"\nThe new snapshot is {Shown(mismatch)}. When it is right, move it over the stored one and commit it.\n")) + .ToString(); + } + + /// <summary>A line diff by the longest common subsequence: ' ' for kept, '-' for stored only, '+' for new only.</summary> + private static List<(char Kind, string Line)> Diff(string[] expected, string[] actual) + { + var lengths = new int[expected.Length + 1, actual.Length + 1]; + for (var i = expected.Length - 1; i >= 0; i--) + { + for (var j = actual.Length - 1; j >= 0; j--) + { + lengths[i, j] = expected[i] == actual[j] + ? lengths[i + 1, j + 1] + 1 + : Math.Max(lengths[i + 1, j], lengths[i, j + 1]); + } + } + + var result = new List<(char, string)>(); + int a = 0, b = 0; + while (a < expected.Length || b < actual.Length) + { + if (a < expected.Length && b < actual.Length && expected[a] == actual[b]) + { + result.Add((' ', expected[a++])); + b++; + } + else if (b < actual.Length && (a == expected.Length || lengths[a, b + 1] > lengths[a + 1, b])) + { + result.Add(('+', actual[b++])); + } + else + { + result.Add(('-', expected[a++])); + } + } + + return result; + } + + /// <summary>The ranges of the diff to show: each changed line with <see cref="ContextLines"/> around it, joined.</summary> + private static IEnumerable<(int Start, int End)> Hunks(List<(char Kind, string Line)> diff) + { + var changed = diff.Select((entry, index) => (entry.Kind, index)).Where(entry => entry.Kind != ' ') + .Select(entry => entry.index).ToList(); + var i = 0; + while (i < changed.Count) + { + var start = Math.Max(0, changed[i] - ContextLines); + var end = Math.Min(diff.Count, changed[i] + ContextLines + 1); + while (++i < changed.Count && changed[i] - ContextLines <= end) + { + end = Math.Min(diff.Count, changed[i] + ContextLines + 1); + } + + yield return (start, end); + } + } + + // Paths from the root of the repository, the directory with Tazel.slnx, as a reader finds them. + private static string Shown(string path) + { + var root = new DirectoryInfo(Path.GetDirectoryName(path)!); + while (root is not null && !File.Exists(Path.Combine(root.FullName, "Tazel.slnx"))) + { + root = root.Parent; + } + + return (root is null ? path : Path.GetRelativePath(root.FullName, path)).Replace('\\', '/'); + } + + private static string CultureInfoInvariant(FormattableString text) => + text.ToString(System.Globalization.CultureInfo.InvariantCulture); +} diff --git a/tests/Progmasoft.Tazel.Tests/TemporaryModule.cs b/tests/Progmasoft.Tazel.Tests/TemporaryModule.cs new file mode 100644 index 0000000..1a18795 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/TemporaryModule.cs @@ -0,0 +1,64 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Driver; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Tests; + +/// <summary>A directory that is removed after the test, with the files a test writes into it.</summary> +internal sealed class TemporaryModule : IDisposable +{ + public const string ModuleFile = """ + using Progmasoft.Tazel.Dsl.Module.Prelude; + module = Module.Define(new() { Group = "com.example", Name = "sample", Version = "0.1.0" }); + """; + + public TemporaryModule() + { + Root = Path.Combine(Path.GetTempPath(), "tazel-tests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Root); + } + + public string Root { get; } + + /// <summary>Writes <paramref name="text"/> to <paramref name="relative"/>, making its directories.</summary> + public TemporaryModule Write(string relative, string text) + { + var path = Path.Combine(Root, relative); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, text); + return this; + } + + /// <summary>Loads the module as a debug build for this machine.</summary> + public Task<Workspace> LoadAsync(string? directory = null) => + Workspace.LoadAsync(directory ?? Root, new BuildContext(BuildMode.Debug, Host.Platform), new Version(0, 1, 0)); + + /// <summary>Runs tazel with <paramref name="arguments"/> in <paramref name="directory"/>, keeping what it prints.</summary> + public async Task<(int Status, string Output)> TazelAsync(string directory, params string[] arguments) + { + using var output = new StringWriter(); + var status = await Program.RunAsync([.. arguments, "--color", "never"], Path.Combine(Root, directory), output, + Xunit.TestContext.Current.CancellationToken); + return (status, output.ToString()); + } + + public void Dispose() + { + try + { + Directory.Delete(Root, recursive: true); + } + catch (IOException) + { + // A program a test started may still hold a file on Windows; the system's temporary directory keeps it. + } + } +} diff --git a/tests/Progmasoft.Tazel.Tests/TextFileTests.cs b/tests/Progmasoft.Tazel.Tests/TextFileTests.cs new file mode 100644 index 0000000..ad92a1b --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/TextFileTests.cs @@ -0,0 +1,134 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Linq; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Dsl.Custom; +using Progmasoft.Tazel.Dsl.Custom.Parser; +using Progmasoft.Tazel.Dsl.Options; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class CustomCommandTests +{ + private const string Sample = """ + # comment + <# comment #> + build-no-cache: ("tazel" 'build' `--no-cache`); + fetch: + ("cargo" "fetch") + ("tazel" "fetch"); + npm-dev-sh: s('npm dev'); + build no-cache: ("tazel" "build" "--no-cache"); + build with: ("tazel" "build" <1> <2>); + all: ("echo" <*>); + """; + + [Fact] + public void ReadsTheCommandsInTheirOrder() + { + var commands = CustomParser.Parse(Sample); + Assert.Equal(["build-no-cache", "fetch", "npm-dev-sh", "build no-cache", "build with", "all"], + commands.Select(c => c.Name)); + Assert.Equal(2, commands[1].Steps.Count); + Assert.Equal(new CustomStep.Shell("npm dev"), commands[2].Steps[0]); + Assert.Equal(2, commands[4].Required); + Assert.True(commands[5].TakesAll); + } + + [Fact] + public void TheLongestNameThatFitsWins() + { + var commands = CustomParser.Parse(Sample); + var (command, arguments) = commands.Matching(["build", "with", "-e", "MyApp"])!.Value; + Assert.Equal("build with", command.Name); + Assert.Equal(["-e", "MyApp"], arguments); + Assert.Equal(["tazel", "build", "-e", "MyApp"], ((CustomStep.Program)command.Steps[0]).Expanded(arguments)); + } + + [Fact] + public void DashesEndTheName() + { + var commands = CustomParser.Parse(Sample); + var (command, arguments) = commands.Matching(["all", "--", "with"])!.Value; + Assert.Equal("all", command.Name); + Assert.Equal(["with"], arguments); + } + + [Theory] + [InlineData("x: ();", "a command names at least a program")] + [InlineData("x: s(<1>);", "s(...) takes no arguments")] + [InlineData("x: s('a' 'b');", "s(...) takes one string")] + [InlineData("x: (<1> 'a');", "starts with the name of its program")] + [InlineData("x: ('a'); x: ('b');", "defined twice")] + [InlineData("x: ('a' <0>);", "<0> is not an argument")] + [InlineData("x: ('a);", "has no closing '")] + [InlineData("<# x", "no closing #>")] + [InlineData("x: ('a')", "expected ';' at the end of a command")] + [InlineData("x -- y: ('a');", "cannot hold it")] + public void RefusesWhatIsWrongWithItsPlace(string text, string reason) + { + var error = Assert.Throws<CustomCommandsException>(() => CustomParser.Parse(text)); + Assert.Contains(reason, error.Message, StringComparison.Ordinal); + Assert.StartsWith("tazel_custom.txt:", error.Message, StringComparison.Ordinal); + } +} + +public sealed class TazelOptionsTests +{ + [Fact] + public void ReadsEveryOption() + { + var options = TazelOptionsFile.Parse(""" + # comment + sandboxing-with-microvm: true; + microvm-network: false; + microvm-memory: 2048; + microvm-cpus: "auto"; + platform: macos-x86_64 + """); + Assert.True(options.SandboxingWithMicrovm); + Assert.False(options.MicrovmNetwork); + Assert.Equal(new Allocation(2048), options.MicrovmMemory); + Assert.Equal(Allocation.Auto, options.MicrovmCpus); + Assert.Equal(Platform.MacOSX86_64, options.Platform); + } + + [Theory] + [InlineData("platform: linux-x64;", "is not a platform")] + [InlineData("microvm-memory: 100;", "is outside 256 to 1048576 MiB")] + [InlineData("microvm-cpus: 'some';", "the only string here is \"auto\"")] + [InlineData("microvm-network: yes;", "expected true or false")] + [InlineData("microvm-network: true; microvm-network: true;", "is set twice")] + [InlineData("memory: 1;", "is not an option")] + public void RefusesWhatIsWrong(string text, string reason) + { + var error = Assert.Throws<TazelOptionsException>(() => TazelOptionsFile.Parse(text)); + Assert.Contains(reason, error.Message, StringComparison.Ordinal); + } + + [Fact] + public void ASandboxAskedForAboveStaysAskedFor() + { + using var module = new TemporaryModule(); + module.Write("tazel_options.txt", "sandboxing-with-microvm: true;") + .Write("inner/tazel_options.txt", "sandboxing-with-microvm: false; platform: linux-aarch64;"); + var (options, file) = TazelOptionsFile.Effective(Path.Combine(module.Root, "inner")); + Assert.True(options.SandboxingWithMicrovm); + Assert.Equal(Platform.LinuxAarch64, options.Platform); + Assert.Equal(Path.Combine(module.Root, "tazel_options.txt"), file); + } + + [Fact] + public void EveryPlatformNameReadsBack() + { + foreach (var platform in Enum.GetValues<Platform>()) + { + Assert.True(Platforms.TryParse(platform.Name(), out var read)); + Assert.Equal(platform, read); + } + } +} diff --git a/tests/Progmasoft.Tazel.Tests/WorkspaceTests.cs b/tests/Progmasoft.Tazel.Tests/WorkspaceTests.cs new file mode 100644 index 0000000..951d088 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/WorkspaceTests.cs @@ -0,0 +1,127 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Linq; +using System.Threading.Tasks; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Label; +using Progmasoft.Tazel.Project; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class WorkspaceTests +{ + private const string Prelude = "using Progmasoft.Tazel.Dsl.Build.Prelude;\n"; + + [Fact] + public async Task LoadsTheTargetsOfEveryPackage() + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("BUILD.csx", Prelude + """ + var core = CC.StaticLibrary("core", new() { Sources = ["core.c"], Visibility = Visibility.Module }); + CC.Executable("app", new() { Sources = ["main.c"], Depends = [core, "//lib:util"] }); + """) + .Write("core.c", "").Write("main.c", "") + .Write("lib/BUILD.csx", Prelude + """ + CC.StaticLibrary("util", new() { Sources = new Glob("*.c"), Visibility = Visibility.Public }); + """) + .Write("lib/u.c", ""); + var workspace = await module.LoadAsync(); + var app = workspace.Targets[new TargetLabel(PackageId.Root, "app")]; + Assert.Equal(TargetKind.Executable, app.Kind); + Assert.Equal(["//:core", "//lib:util"], app.Dependencies.Select(d => d.Label.ToString())); + Assert.Equal("BUILD.csx:3", app.Place); + Assert.Equal(["//", "//lib"], workspace.Packages.Select(p => p.ToString()).Order(StringComparer.Ordinal)); + } + + [Theory] + [InlineData("CC.Executable(\"a\", new() { Depends = [\":nope\"] });", "depends on //:nope, which is not declared")] + [InlineData("CC.Executable(\"a\", new() { Depends = [\":b\"] }); CC.Executable(\"b\", new());", "only libraries are linked")] + [InlineData("CC.StaticLibrary(\"a\", new()); CC.StaticLibrary(\"a\", new());", "'a' is declared twice")] + [InlineData("CC.StaticLibrary(\"a\", new() { Depends = [\":b\"] }); CC.StaticLibrary(\"b\", new() { Depends = [\":a\"] });", "depend on each other")] + [InlineData("CC.StaticLibrary(\"bad name\", new());", "must be letters")] + [InlineData("CC.StaticLibrary(\"a\", new() { Sources = [\"missing.c\"] });", "")] + [InlineData("CC.StaticLibrary(\"a\", new() { Nope = 1 });", "BUILD.csx:2:")] + [InlineData("throw new System.InvalidOperationException(\"no\");", "InvalidOperationException: no")] + public async Task ReportsWhatIsWrongWithItsPlace(string body, string message) + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", TemporaryModule.ModuleFile).Write("BUILD.csx", Prelude + body); + if (message.Length == 0) + { + // A missing source is found when the target is planned, not when the file runs. + var workspace = await module.LoadAsync(); + Assert.Single(workspace.Targets); + return; + } + + var error = await Assert.ThrowsAsync<ProjectException>(() => module.LoadAsync()); + Assert.Contains(message, error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task APrivateTargetIsSeenOnlyInItsFile() + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("BUILD.csx", Prelude + "CC.Executable(\"app\", new() { Depends = [\"//lib:hidden\"] });") + .Write("lib/BUILD.csx", Prelude + "CC.StaticLibrary(\"hidden\", new());"); + var error = await Assert.ThrowsAsync<ProjectException>(() => module.LoadAsync()); + Assert.Contains("//lib:hidden is private", error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task AModuleFileMustDefineAValidModule() + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", """ + using Progmasoft.Tazel.Dsl.Module.Prelude; + module = Module.Define(new() { Group = "com.example", Name = "x", Version = "1.2" }); + """); + var error = await Assert.ThrowsAsync<ProjectException>(() => module.LoadAsync()); + Assert.Contains("'1.2' is not a SemVer version", error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task AModuleSaysWhichTazelItBuildsWith() + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", """ + using Progmasoft.Tazel.Dsl.Module.Prelude; + module = Module.Define(new() { Group = "com.example", Name = "x", Version = "1.0.0", + Compatibility = TazelVersion.AtLeast(9, 0) }); + """); + var error = await Assert.ThrowsAsync<ProjectException>(() => module.LoadAsync()); + Assert.Contains("builds with Tazel 9.0.0 or later; this is Tazel 0.1.0", error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task ObjectiveCTargetsBuildForMacOSUnlessTheySayOtherwise() + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", TemporaryModule.ModuleFile).Write("BUILD.csx", Prelude + """ + ObjectiveC.StaticLibrary("mac", new()); + ObjectiveC.StaticLibrary("gnustep", new() { TargetConstraints = [Platform.LinuxAmd64] }); + """); + var workspace = await module.LoadAsync(); + var mac = workspace.Targets[new TargetLabel(PackageId.Root, "mac")]; + var gnustep = workspace.Targets[new TargetLabel(PackageId.Root, "gnustep")]; + Assert.True(mac.BuildsFor(Dsl.Common.Platform.MacOSArm64)); + Assert.False(mac.BuildsFor(Dsl.Common.Platform.LinuxAmd64)); + Assert.True(gnustep.BuildsFor(Dsl.Common.Platform.LinuxAmd64)); + } + + [Fact] + public async Task ARegisteredToolchainMustBeDeclared() + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", TemporaryModule.ModuleFile + "\ntoolchains = Toolchains.Define(\"//toolchains:clang\");") + .Write("toolchains/BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Toolchain.Prelude;\n"); + var error = await Assert.ThrowsAsync<ProjectException>(() => module.LoadAsync()); + Assert.Contains("no toolchain //toolchains:clang is declared", error.Message, StringComparison.Ordinal); + } +} diff --git a/tests/Progmasoft.Tazel.Tests/__snapshots__/PlannerTests.TheCommandsOfABuild.snap b/tests/Progmasoft.Tazel.Tests/__snapshots__/PlannerTests.TheCommandsOfABuild.snap new file mode 100644 index 0000000..d9d5ef3 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/__snapshots__/PlannerTests.TheCommandsOfABuild.snap @@ -0,0 +1,211 @@ +[ + { + "Description": "Compiling //:app src/main.cc", + "Arguments": [ + "-g", + "-Wall", + "-I.", + "-Iinclude", + "-DMATH_API=1", + "-DFROM_COMMAND_LINE", + "-MD", + "-MF", + ".tazel/out/linux-amd64-debug/_objs/app/src/main.cc.o.d", + "-c", + "src/main.cc", + "-o", + ".tazel/out/linux-amd64-debug/_objs/app/src/main.cc.o" + ], + "Inputs": [ + "src/main.cc", + "include/math.hpp" + ], + "Outputs": [ + ".tazel/out/linux-amd64-debug/_objs/app/src/main.cc.o" + ] + }, + { + "Description": "Compiling //:math src/a.cpp", + "Arguments": [ + "-g", + "-Wall", + "-fPIC", + "-I.", + "-Iinclude", + "-DMATH_API=1", + "-DMATH_BUILD=1", + "-std=c++23", + "-DFROM_COMMAND_LINE", + "-MD", + "-MF", + ".tazel/out/linux-amd64-debug/_objs/math/src/a.cpp.o.d", + "-c", + "src/a.cpp", + "-o", + ".tazel/out/linux-amd64-debug/_objs/math/src/a.cpp.o" + ], + "Inputs": [ + "src/a.cpp", + "include/math.hpp" + ], + "Outputs": [ + ".tazel/out/linux-amd64-debug/_objs/math/src/a.cpp.o" + ] + }, + { + "Description": "Compiling //:math src/b.cpp", + "Arguments": [ + "-g", + "-Wall", + "-fPIC", + "-I.", + "-Iinclude", + "-DMATH_API=1", + "-DMATH_BUILD=1", + "-std=c++23", + "-DFROM_COMMAND_LINE", + "-MD", + "-MF", + ".tazel/out/linux-amd64-debug/_objs/math/src/b.cpp.o.d", + "-c", + "src/b.cpp", + "-o", + ".tazel/out/linux-amd64-debug/_objs/math/src/b.cpp.o" + ], + "Inputs": [ + "src/b.cpp", + "include/math.hpp" + ], + "Outputs": [ + ".tazel/out/linux-amd64-debug/_objs/math/src/b.cpp.o" + ] + }, + { + "Description": "Archiving //:math", + "Arguments": [ + "rcsD", + ".tazel/out/linux-amd64-debug/libmath.a", + ".tazel/out/linux-amd64-debug/_objs/math/src/a.cpp.o", + ".tazel/out/linux-amd64-debug/_objs/math/src/b.cpp.o" + ], + "Inputs": [ + ".tazel/out/linux-amd64-debug/_objs/math/src/a.cpp.o", + ".tazel/out/linux-amd64-debug/_objs/math/src/b.cpp.o" + ], + "Outputs": [ + ".tazel/out/linux-amd64-debug/libmath.a" + ] + }, + { + "Description": "Compiling //:shared src/shared.c", + "Arguments": [ + "-g", + "-fPIC", + "-I.", + "-Iinclude", + "-DMATH_API=1", + "-std=c17", + "-DFROM_COMMAND_LINE", + "-MD", + "-MF", + ".tazel/out/linux-amd64-debug/_objs/shared/src/shared.c.o.d", + "-c", + "src/shared.c", + "-o", + ".tazel/out/linux-amd64-debug/_objs/shared/src/shared.c.o" + ], + "Inputs": [ + "src/shared.c", + "include/math.hpp" + ], + "Outputs": [ + ".tazel/out/linux-amd64-debug/_objs/shared/src/shared.c.o" + ] + }, + { + "Description": "Linking //:shared", + "Arguments": [ + "-g", + "-flto", + "-shared", + "-Wl,-soname,libshared.so.1", + "-o", + ".tazel/out/linux-amd64-debug/libshared.so.1.2.0", + ".tazel/out/linux-amd64-debug/_objs/shared/src/shared.c.o", + "-Wl,--whole-archive", + ".tazel/out/linux-amd64-debug/libmath.a", + "-Wl,--no-whole-archive", + "-lm", + "-Wl,--as-needed" + ], + "Inputs": [ + ".tazel/out/linux-amd64-debug/_objs/shared/src/shared.c.o", + ".tazel/out/linux-amd64-debug/libmath.a" + ], + "Outputs": [ + ".tazel/out/linux-amd64-debug/libshared.so.1.2.0" + ] + }, + { + "Description": "Linking //:app", + "Arguments": [ + "-g", + "-o", + ".tazel/out/linux-amd64-debug/app", + ".tazel/out/linux-amd64-debug/_objs/app/src/main.cc.o", + "-Wl,--whole-archive", + ".tazel/out/linux-amd64-debug/libmath.a", + "-Wl,--no-whole-archive", + ".tazel/out/linux-amd64-debug/libshared.so.1.2.0", + "-Wl,-rpath,$ORIGIN", + "-lm", + "-Wl,--as-needed" + ], + "Inputs": [ + ".tazel/out/linux-amd64-debug/_objs/app/src/main.cc.o", + ".tazel/out/linux-amd64-debug/libmath.a", + ".tazel/out/linux-amd64-debug/libshared.so.1.2.0" + ], + "Outputs": [ + ".tazel/out/linux-amd64-debug/app" + ] + }, + { + "Description": "Compiling //:zapp", + "Arguments": [ + "build-exe", + "--cache-dir", + ".tazel/zig-cache", + "-femit-bin=.tazel/out/linux-amd64-debug/zapp", + "-lc", + ".tazel/out/linux-amd64-debug/libmath.a", + "-lm", + "-Wl,--as-needed", + "-O", + "Debug", + "-I.", + "-Iinclude", + "-cflags", + "-g", + "-std=c17", + "-DFROM_COMMAND_LINE", + "--", + "zig/shim.c", + "--dep", + "core=core", + "-Mroot=zig/main.zig", + "-O", + "Debug", + "-Mcore=zig/core.zig" + ], + "Inputs": [ + "zig/main.zig", + "zig/core.zig", + "zig/shim.c", + ".tazel/out/linux-amd64-debug/libmath.a" + ], + "Outputs": [ + ".tazel/out/linux-amd64-debug/zapp" + ] + } +]