master a68000002745 cached
77 files
31.7 MB
183.7k tokens
74 symbols
1 requests
Download .txt
Showing preview only (850K chars total). Download the full file or copy to clipboard to get everything.
Repository: tree-sitter/tree-sitter-scala
Branch: master
Commit: a68000002745
Files: 77
Total size: 31.7 MB

Directory structure:
gitextract_igzcqol5/

├── .editorconfig
├── .envrc
├── .git-blame-ignore-revs
├── .gitattributes
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   └── bug_report.yml
│   └── workflows/
│       ├── ci.yml
│       ├── fuzz.yml
│       ├── publish.yml
│       └── sync.yml
├── .gitignore
├── .prettierrc.json
├── CMakeLists.txt
├── CONTRIBUTING.md
├── Cargo.toml
├── LICENSE
├── Makefile
├── Package.resolved
├── Package.swift
├── README.md
├── binding.gyp
├── bindings/
│   ├── c/
│   │   ├── tree-sitter-scala.h
│   │   ├── tree-sitter-scala.pc.in
│   │   └── tree_sitter/
│   │       └── tree-sitter-scala.h
│   ├── go/
│   │   ├── binding.go
│   │   └── binding_test.go
│   ├── node/
│   │   ├── binding.cc
│   │   ├── binding_test.js
│   │   ├── index.d.ts
│   │   └── index.js
│   ├── python/
│   │   ├── tests/
│   │   │   └── test_binding.py
│   │   └── tree_sitter_scala/
│   │       ├── __init__.py
│   │       ├── __init__.pyi
│   │       ├── binding.c
│   │       └── py.typed
│   ├── rust/
│   │   ├── build.rs
│   │   └── lib.rs
│   └── swift/
│       ├── TreeSitterScala/
│       │   └── scala.h
│       └── TreeSitterScalaTests/
│           └── TreeSitterScalaTests.swift
├── examples/
│   ├── Packages.scala
│   ├── PathResolver.scala
│   ├── RefChecks.scala
│   ├── SyntaxAnalyzer.scala
│   └── Variance.scala
├── go.mod
├── go.sum
├── grammar.js
├── package.json
├── pyproject.toml
├── queries/
│   ├── highlights.scm
│   ├── indents.scm
│   ├── locals.scm
│   └── tags.scm
├── script/
│   ├── parse-with-scalac
│   └── smoke_test.sh
├── setup.py
├── src/
│   ├── grammar.json
│   ├── node-types.json
│   ├── parser.c
│   ├── scanner.c
│   └── tree_sitter/
│       ├── alloc.h
│       ├── array.h
│       └── parser.h
├── test/
│   ├── corpus/
│   │   ├── annotations.txt
│   │   ├── comments.txt
│   │   ├── definitions-pending.txt
│   │   ├── definitions.txt
│   │   ├── expressions.txt
│   │   ├── literals.txt
│   │   ├── patterns-pending.txt
│   │   ├── patterns.txt
│   │   ├── types-pending.txt
│   │   └── types.txt
│   ├── highlight/
│   │   ├── basics.scala
│   │   ├── comments.scala
│   │   └── scala3.scala
│   └── tags/
│       └── basics.scala
└── tree-sitter.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .editorconfig
================================================
root = true

[*]
charset = utf-8

[*.{json,toml,yml,gyp}]
indent_style = space
indent_size = 2

[*.js]
indent_style = space
indent_size = 2

[*.scm]
indent_style = space
indent_size = 2

[*.{c,cc,h}]
indent_style = space
indent_size = 4

[*.rs]
indent_style = space
indent_size = 4

[*.{py,pyi}]
indent_style = space
indent_size = 4

[*.swift]
indent_style = space
indent_size = 4

[*.go]
indent_style = tab
indent_size = 8

[Makefile]
indent_style = tab
indent_size = 8

[parser.c]
indent_size = 2

[{alloc,array,parser}.h]
indent_size = 2


================================================
FILE: .envrc
================================================
use nix


================================================
FILE: .git-blame-ignore-revs
================================================
# Move queries to ./queries/scala sub-directory
889eb65aea8e0f9ce1694ab9ee528df1fa5f75d1

# Formatting using Prettier
0a8ca4c836d7e9f0fd6a0668088c0d82874abc85


================================================
FILE: .gitattributes
================================================
* text=auto eol=lf

# Generated source files
src/*.json linguist-generated
src/parser.c linguist-generated
src/tree_sitter/* linguist-generated

# C bindings
bindings/c/* linguist-generated
CMakeLists.txt linguist-generated
Makefile linguist-generated

# Rust bindings
bindings/rust/* linguist-generated
Cargo.toml linguist-generated
Cargo.lock linguist-generated

# Node.js bindings
bindings/node/* linguist-generated
binding.gyp linguist-generated
package.json linguist-generated
package-lock.json linguist-generated

# Python bindings
bindings/python/** linguist-generated
setup.py linguist-generated
pyproject.toml linguist-generated

# Go bindings
bindings/go/* linguist-generated
go.mod linguist-generated
go.sum linguist-generated

# Swift bindings
bindings/swift/** linguist-generated
Package.swift linguist-generated
Package.resolved linguist-generated


================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.yml
================================================
name: Bug Report
description: Create an issue in tree-sitter-scala
body:
  - type: input
    id: commit
    attributes:
      label: Commit of tree-sitter-scala you tested this on
      description: |
        Make sure you're validating you're on the latest commit of
        tree-sitter-scala. Note that depending on where you're experiencing the
        issue there is a chance you're on an old commit.
    validations:
      required: true

  - type: textarea
    id: code-sample
    attributes:
      label: A code sample showing the error
      description: Try to minimize the code sample as much as possible
      placeholder: |
        ```scala
          val y = x match {
            case A(_) if a => 1
          }
        ```
    validations:
      required: true

  - type: textarea
    id: error
    attributes:
      label: Show the error node
      description: Show us the output and where the ERROR node is appearing
      placeholder: |
        Check out [Obtaining an Error Reproduction](../../CONTRIBUTING.md#obtaining-an-error-reproduction)
        in the CONTRIBUTING docs if you're unsure how to get this.

        ```
        (compilation_unit [0, 0] - [4, 0]
          (val_definition [0, 0] - [2, 1]
            pattern: (identifier [0, 4] - [0, 5])
            value: (match_expression [0, 8] - [2, 1]
              value: (identifier [0, 8] - [0, 9])
              body: (case_block [0, 16] - [2, 1]
                (ERROR [1, 2] - [2, 0]
                  (case_class_pattern [1, 7] - [1, 11]
                    type: (type_identifier [1, 7] - [1, 8])
                    pattern: (wildcard [1, 9] - [1, 10]))
                  (lambda_expression [1, 15] - [2, 0]
                    (identifier [1, 15] - [1, 16])
                    (integer_literal [1, 20] - [1, 21])))))))
        ```
    validations:
      required: true

  - type: textarea
    id: expectation
    attributes:
      label: What do you expect the tree to look like
      description: Show us what you expect the tree to look like

  - type: input
    id: where
    attributes:
      label: Where are you experiencing this error?
      description: Let us know where you're seeing this error (nvim-treesitter etc)


================================================
FILE: .github/workflows/ci.yml
================================================
name: Build/test
on:
  push:
  pull_request:
    branches:
      - master

jobs:
  changedfiles:
    runs-on: ubuntu-latest
    outputs:
      all: ${{ steps.changes.outputs.all}}
      c: ${{ steps.changes.outputs.c }}
      gen: ${{ steps.changes.outputs.gen }}
    steps:
      - name: checkout tree-sitter-scala
        uses: actions/checkout@v6
        with:
          fetch-depth: 10

      - name: Get changed files
        id: changes
        run: |
          echo "all=$(git diff --name-only --diff-filter=ACMRT ${{ github.event.pull_request.base.sha }} ${{ github.sha }} | xargs)" >> $GITHUB_OUTPUT
          echo "c=$(git diff --name-only --diff-filter=ACMRT ${{ github.event.pull_request.base.sha }} ${{ github.sha }} | grep '\.\(c\|h\)$' | xargs)" >> $GITHUB_OUTPUT
          # Generated C code
          echo "gen=$(git diff --name-only --diff-filter=ACMRT ${{ github.event.pull_request.base.sha }} ${{ github.sha }} | grep '\.\(c\)$' | grep -v 'src/scanner.c' | grep -v 'bindings/python/tree_sitter_scala/binding.c' | xargs)" >> $GITHUB_OUTPUT

  test:
    runs-on: ${{ matrix.os }}
    needs: changedfiles
    strategy:
      fail-fast: true
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
    steps:
      - name: checkout tree-sitter-scala
        uses: actions/checkout@v6
        with:
          fetch-depth: 10

      - name: checkout scala/scala
        if: ${{ runner.os == 'Linux' }}
        uses: actions/checkout@v6
        with:
          repository: scala/scala
          ref: v2.13.14
          path: scala_scala

      - name: checkout scala/scala3
        if: ${{ runner.os == 'Linux' }}
        uses: actions/checkout@v6
        with:
          repository: scala/scala3
          ref: 3.5.2
          path: dotty

      - name: checkout lichess-org/lila
        if: ${{ runner.os == 'Linux' }}
        uses: actions/checkout@v6
        with:
          repository: lichess-org/lila
          ref: 83e61b9ef617164fe1d3a5112fcc611d0e5a7ea9
          path: lila

      - name: checkout nvim-treesitter/nvim-treesitter
        if: ${{ runner.os == 'Linux' }}
        uses: actions/checkout@v6
        with:
          repository: nvim-treesitter/nvim-treesitter
          path: nvim_treesitter

      - uses: actions/setup-node@v6
        with:
          node-version: 24

      - name: Set up tree-sitter
        uses: tree-sitter/setup-action/cli@v2
        with:
          # Change also on sync.yaml
          tree-sitter-ref: v0.26.8

      - name: Generate parser from scratch and test it
        shell: bash
        run: tree-sitter generate

      - name: Run parser and binding tests
        uses: tree-sitter/parser-test-action@v2
        with:
          generate: false
          test-rust: true
          test-node: false
          test-python: true
          test-go: true
          test-swift: false

      - name: Parse sample files
        uses: tree-sitter/parse-action@v4
        id: parse-files
        with:
          files: examples/**

      - name: Check fidelity of checked-in C code
        if: ${{ runner.os == 'Linux' && needs.changedfiles.outputs.gen }}
        shell: bash
        run: |
          # `git diff --quiet` doesn't seem to work on Github Actions
          changes=$(git diff --name-only --diff-filter=ACMRT | xargs)
          if [ ! -z "$changes" ]; then
            echo "::error file=grammar.js::Generated $changes differs from the checked in version"
            git diff --exit-code
            exit 1
          fi

      - name: Smoke test
        if: ${{ runner.os == 'Linux' }}
        shell: bash
        env:
          SCALA_SCALA_DIR: scala_scala
          DOTTY_DIR: dotty
          LILA_DIR: lila
        run: script/smoke_test.sh

      - name: Check that prettier exists
        if: ${{ runner.os == 'Linux' }}
        run: |
          npm install
          export PATH=./node_modules/.bin:$PATH
          prettier --write --ignore-unknown grammar.js

      - name: copy nvim-treesitter queries
        if: ${{ runner.os == 'Linux' }}
        shell: bash
        run: cp ./nvim_treesitter/runtime/queries/scala/*.scm ./queries/

      - name: Check if queries are out of sync with nvim-treesitter
        if: ${{ runner.os == 'Linux' }}
        uses: tj-actions/verify-changed-files@v19
        id: verify-changed-files
        with:
          files: |
            queries/*.scm

      # TODO: uncomment when this works
      # - name: Test quries if out of sync with nvim-treesitter
      #   if: steps.verify-changed-files.outputs.files_changed == 'true'
      #   run: |
      #     echo "::warning Queries in ${{ steps.verify-changed-files.outputs.changed_files }} in this repo are out of sync with nvim-treesitter"
      #     git diff queries/
      #     npm run test


================================================
FILE: .github/workflows/fuzz.yml
================================================
name: Fuzz Parser

on:
  push:
    branches: [master]
    paths:
      - src/scanner.c
  pull_request:
    paths:
      - src/scanner.c

jobs:
  fuzz:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
      - name: Run fuzzer
        uses: tree-sitter/fuzz-action@v4


================================================
FILE: .github/workflows/publish.yml
================================================
name: Publish packages

on:
  push:
    tags: ["*"]

permissions:
  contents: write
  id-token: write
  attestations: write

jobs:
  github:
    uses: tree-sitter/workflows/.github/workflows/release.yml@6a7388cecfbc00765d032b2fca8f8abbe092ae8d
    with:
      generate: true
  npm:
    uses: tree-sitter/workflows/.github/workflows/package-npm.yml@6a7388cecfbc00765d032b2fca8f8abbe092ae8d
    secrets:
      NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
    with:
      generate: true
  crates:
    uses: tree-sitter/workflows/.github/workflows/package-crates.yml@6a7388cecfbc00765d032b2fca8f8abbe092ae8d
    secrets:
      CARGO_REGISTRY_TOKEN: ${{secrets.CARGO_REGISTRY_TOKEN}}
    with:
      generate: true
  pypi:
    uses: tree-sitter/workflows/.github/workflows/package-pypi.yml@6a7388cecfbc00765d032b2fca8f8abbe092ae8d
    secrets:
      PYPI_API_TOKEN: ${{secrets.PYPI_API_TOKEN}}
    with:
      generate: true


================================================
FILE: .github/workflows/sync.yml
================================================
name: "Check changes and sync"
on:
  workflow_dispatch:
  schedule:
    - cron: 0 5 * * *

jobs:
  check-and-sync:
    runs-on: ubuntu-latest
    if: github.repository == 'tree-sitter/tree-sitter-scala'
    outputs:
      all: ${{ steps.changes.outputs.all}}
      c: ${{ steps.changes.outputs.c }}
    steps:
      - name: checkout tree-sitter-scala
        uses: actions/checkout@v6
        with:
          fetch-depth: 10

      - name: Set up tree-sitter
        uses: tree-sitter/setup-action/cli@v2
        with:
          tree-sitter-ref: v0.26.8

      - name: Generate parser from scratch
        shell: bash
        run: tree-sitter generate

      - name: Format Javascipt
        run: |
          npm install
          export PATH=./node_modules/.bin:$PATH
          prettier --write --ignore-unknown grammar.js

      - name: Check for changes
        uses: tj-actions/verify-changed-files@v19
        id: verify-changed-files
        with:
          files: |
            bindings/c/tree-sitter-scala.h
            bindings/c/tree-sitter-scala.pc.in
            grammar.js
            src/grammar.json
            src/node-types.json
            src/parser.c
            src/tree_sitter/alloc.h
            src/tree_sitter/array.h
            src/tree_sitter/parser.h

      - name: Commit changes if necessary
        if: steps.verify-changed-files.outputs.files_changed == 'true'
        run: |
          git config user.name "GitHub"
          git config user.email "noreply@github.com"
          git add .
          LAST_COMMIT=$(git log --format="%H" -n 1)
          git commit -m "chore: generate and sync from $LAST_COMMIT"
          git clean -xf

      - name: Create Pull Request
        if: steps.verify-changed-files.outputs.files_changed == 'true'
        uses: peter-evans/create-pull-request@v8
        with:
          title: "chore: generate and sync latest changes"
          branch: generation
          base: ${{ github.head_ref }}

      - name: No changes detected
        if: steps.verify-changed-files.outputs.files_changed == 'false'
        run: echo "No changes detected"


================================================
FILE: .gitignore
================================================
# Rust artifacts
target/

# Node artifacts
build/
prebuilds/
node_modules/

# Swift artifacts
.build/

# Go artifacts
_obj/

# Python artifacts
.venv/
dist/
*.egg-info
*.whl

# C artifacts
*.a
*.so
*.so.*
*.dylib
*.dll
*.pc

# Example dirs
/examples/*/

# Grammar volatiles
*.wasm
*.obj
*.o

# Archives
*.tar.gz
*.tgz
*.zip

# Scala tooling
.metals
.bsp
.scala-build

# AI assistants
.aider*


================================================
FILE: .prettierrc.json
================================================
{
  "arrowParens": "avoid"
}


================================================
FILE: CMakeLists.txt
================================================
cmake_minimum_required(VERSION 3.13)

project(tree-sitter-scala
        VERSION "0.26.0"
        DESCRIPTION "Scala grammar for tree-sitter"
        HOMEPAGE_URL "https://github.com/tree-sitter/tree-sitter-scala"
        LANGUAGES C)

option(BUILD_SHARED_LIBS "Build using shared libraries" ON)
option(TREE_SITTER_REUSE_ALLOCATOR "Reuse the library allocator" OFF)

set(TREE_SITTER_ABI_VERSION 15 CACHE STRING "Tree-sitter ABI version")
if(NOT ${TREE_SITTER_ABI_VERSION} MATCHES "^[0-9]+$")
    unset(TREE_SITTER_ABI_VERSION CACHE)
    message(FATAL_ERROR "TREE_SITTER_ABI_VERSION must be an integer")
endif()

include(GNUInstallDirs)

find_program(TREE_SITTER_CLI tree-sitter DOC "Tree-sitter CLI")

add_custom_command(OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/src/grammar.json"
                          "${CMAKE_CURRENT_SOURCE_DIR}/src/node-types.json"
                   DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/grammar.js"
                   COMMAND "${TREE_SITTER_CLI}" generate grammar.js --no-parser
                   WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
                   COMMENT "Generating grammar.json")

add_custom_command(OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/src/parser.c"
                   BYPRODUCTS "${CMAKE_CURRENT_SOURCE_DIR}/src/tree_sitter/parser.h"
                              "${CMAKE_CURRENT_SOURCE_DIR}/src/tree_sitter/alloc.h"
                              "${CMAKE_CURRENT_SOURCE_DIR}/src/tree_sitter/array.h"
                   DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/grammar.json"
                   COMMAND "${TREE_SITTER_CLI}" generate src/grammar.json
                            --abi=${TREE_SITTER_ABI_VERSION}
                   WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
                   COMMENT "Generating parser.c")

add_library(tree-sitter-scala src/parser.c)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/src/scanner.c)
  target_sources(tree-sitter-scala PRIVATE src/scanner.c)
endif()
target_include_directories(tree-sitter-scala
                           PRIVATE src
                           INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/bindings/c>
                                     $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)

target_compile_definitions(tree-sitter-scala PRIVATE
                           $<$<BOOL:${TREE_SITTER_REUSE_ALLOCATOR}>:TREE_SITTER_REUSE_ALLOCATOR>
                           $<$<CONFIG:Debug>:TREE_SITTER_DEBUG>)

set_target_properties(tree-sitter-scala
                      PROPERTIES
                      C_STANDARD 11
                      POSITION_INDEPENDENT_CODE ON
                      SOVERSION "${TREE_SITTER_ABI_VERSION}.${PROJECT_VERSION_MAJOR}"
                      DEFINE_SYMBOL "")

configure_file(bindings/c/tree-sitter-scala.pc.in
               "${CMAKE_CURRENT_BINARY_DIR}/tree-sitter-scala.pc" @ONLY)

install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/bindings/c/tree_sitter"
        DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
        FILES_MATCHING PATTERN "*.h")
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/tree-sitter-scala.pc"
        DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
install(TARGETS tree-sitter-scala
        LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}")

file(GLOB QUERIES queries/*.scm)
install(FILES ${QUERIES}
        DESTINATION "${CMAKE_INSTALL_DATADIR}/tree-sitter/queries/scala")

add_custom_target(ts-test "${TREE_SITTER_CLI}" test
                  WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
                  COMMENT "tree-sitter test")


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to tree-sitter-scala

First off, thanks for being willing to contribute to making syntax highlighting
in Scala better! This document will hopefully help you get set up, understand
how to work on the codebase, or link to places to help you understand
tree-sitter.

## Requirements

- [tree-sitter CLI](https://github.com/tree-sitter/tree-sitter/tree/master/cli)
- Node.js version 18.0 or greater
- C Compiler

Refer to the [tree-sitter
documentation](https://tree-sitter.github.io/tree-sitter/creating-parsers/1-getting-started.html)
for more details and specifics.

If you use nix you can enter a nix-shell (`nix-shell .`) which will install them
for you.

## Getting Started

To get started with contributing to the grammar you'll first need to install the
project's dependencies:

```sh
npm install
```

The general flow will often start with adding a test case to `./test/corpus`. You can
find details on how testing works with tree-sitter
[here](https://tree-sitter.github.io/tree-sitter/creating-parsers/5-writing-tests.html).

Once you've added your test case you'll want to then make the required changes
to `grammar.js`, regenerate and recompile the parser, and run the tests:

```sh
tree-sitter generate
tree-sitter test
```

Then adjust as necessary. Note that depending on your change you may also have
to touch the `/src/scanner.c` file if you need more advanced features like
look-ahead.

## Pending Tests

In `./test/corpus`, there are several files named `*-pending.txt`. These contain tests labeled with `:skip`, meaning they are not currently run. Each test includes examples of valid Scala syntax that `tree-sitter-scala` is known to fail to parse. If you’d like to contribute to `tree-sitter-scala`, a good place to start is by trying to fix one of these tests.

## Syntax highlighting

Right now the most common use-case for syntax highlight using tree-sitter is
[nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter), which
means much of our testing is in relation to it. You can find the syntax
highlighting tests in `test/highlight/*.scala`. You can read more about this
type of testing 
[here](https://tree-sitter.github.io/tree-sitter/3-syntax-highlighting.html#unit-testing). 
These test will be run automatically with `tree-sitter test`.

### tree-sitter highlight

Another way to test your syntax highlighting locally is to use the `tree-sitter
highlight` command. Note that you'll need to have `tree-sitter` installed
globally for this to work. Once you have it installed you'll want to follow the
instructions [here](https://tree-sitter.github.io/tree-sitter/3-syntax-highlighting.html#overview) 
to setup a local config that points towards this repo to be used as a parser. 
Once done you can then do the following:

```sh
tree-sitter highlight some/scala/file.scala
```

And see the syntax highlighting spit out. This is also the format used for
testing, so it provides an easy way to get the output we use for testing.

## Generation

In order to help not cause conflicts with multiple prs being open at the same
time, we don't check in the parser on each pr. Instead, just check in the
changes to the `grammar.js` and the CI will take care of the rest. Each night if
changes are detected it will automatically be generated.

## Smoke testing

You'll noticed that there is a part of CI that checks parsing against the Scala
2 and Scala 3 repositories to ensure we don't introduce unexpected regressions.
The script for this is in `script/smoke_test.sh`. If you're change is increasing
the coverage in either the library or compiler, please do update the expected
percentages at the top of the file.

## Obtaining an error reproduction

_With Neovim_

When creating an issue you'll want to ensure to include the `ERROR` node in it's
context. There's a couple ways to do this. If you're using Neovim and utilizing
treesitter, you can see the tree with `:lua vim.treesitter.show_tree()`. You can
copy it directly from the open panel.

_Manually_

A manual way to get this would be to ensure that when you're in the repo you
have the latest parser with

```sh
npm run build
```

Then you can copy your Scala code in a file and pass that file into `npm run
parse`:

```
tree-sitter parse <path/to/your/file.scala>
```

Then the tree will be printed out for you to copy.

## Release

1. Update `version` in `tree-sitte.json`
2. Update `version` in `package.json`, then run `npm install`
3. Update `VERSION` in `CMakeLists.txt`
4. Update `VERSION` in `Makefile`
5. Update `version` in `Cargo.toml`, then run `cargo build`
6. Update `version` in `pyproject.toml`


================================================
FILE: Cargo.toml
================================================
[package]
name = "tree-sitter-scala"
description = "Scala grammar for tree-sitter"
version = "0.26.0"
authors = ["Max Brunsfeld <maxbrunsfeld@gmail.com>"]
license = "MIT"
readme = "README.md"
keywords = ["incremental", "parsing", "tree-sitter", "scala"]
categories = ["parsing", "text-editors"]
repository = "https://github.com/tree-sitter/tree-sitter-scala"
edition = "2021"
autoexamples = false

build = "bindings/rust/build.rs"
include = ["LICENSE", "bindings/rust/*", "grammar.js", "queries/*", "src/*", "tree-sitter.json"]

[lib]
path = "bindings/rust/lib.rs"

[dependencies]
tree-sitter-language = "0.1"

[build-dependencies]
cc = "1.1"

[dev-dependencies]
tree-sitter = "0.26"


================================================
FILE: LICENSE
================================================
The MIT License (MIT)

Copyright (c) 2018 Max Brunsfeld and GitHub

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: Makefile
================================================
ifeq ($(OS),Windows_NT)
$(error Windows is not supported)
endif

LANGUAGE_NAME := tree-sitter-scala
HOMEPAGE_URL := https://github.com/tree-sitter/tree-sitter-scala
VERSION := 0.26.0

# repository
SRC_DIR := src

TS ?= tree-sitter

# install directory layout
PREFIX ?= /usr/local
INCLUDEDIR ?= $(PREFIX)/include
LIBDIR ?= $(PREFIX)/lib
PCLIBDIR ?= $(LIBDIR)/pkgconfig

# source/object files
PARSER := $(SRC_DIR)/parser.c
EXTRAS := $(filter-out $(PARSER),$(wildcard $(SRC_DIR)/*.c))
OBJS := $(patsubst %.c,%.o,$(PARSER) $(EXTRAS))

# flags
ARFLAGS ?= rcs
override CFLAGS += -I$(SRC_DIR) -std=c11 -fPIC

# ABI versioning
SONAME_MAJOR = $(shell sed -n 's/\#define LANGUAGE_VERSION //p' $(PARSER))
SONAME_MINOR = $(word 1,$(subst ., ,$(VERSION)))

# OS-specific bits
ifeq ($(shell uname),Darwin)
	SOEXT = dylib
	SOEXTVER_MAJOR = $(SONAME_MAJOR).$(SOEXT)
	SOEXTVER = $(SONAME_MAJOR).$(SONAME_MINOR).$(SOEXT)
	LINKSHARED = -dynamiclib -Wl,-install_name,$(LIBDIR)/lib$(LANGUAGE_NAME).$(SOEXTVER),-rpath,@executable_path/../Frameworks
else
	SOEXT = so
	SOEXTVER_MAJOR = $(SOEXT).$(SONAME_MAJOR)
	SOEXTVER = $(SOEXT).$(SONAME_MAJOR).$(SONAME_MINOR)
	LINKSHARED = -shared -Wl,-soname,lib$(LANGUAGE_NAME).$(SOEXTVER)
endif
ifneq ($(filter $(shell uname),FreeBSD NetBSD DragonFly),)
	PCLIBDIR := $(PREFIX)/libdata/pkgconfig
endif

all: lib$(LANGUAGE_NAME).a lib$(LANGUAGE_NAME).$(SOEXT) $(LANGUAGE_NAME).pc

lib$(LANGUAGE_NAME).a: $(OBJS)
	$(AR) $(ARFLAGS) $@ $^

lib$(LANGUAGE_NAME).$(SOEXT): $(OBJS)
	$(CC) $(LDFLAGS) $(LINKSHARED) $^ $(LDLIBS) -o $@
ifneq ($(STRIP),)
	$(STRIP) $@
endif

$(LANGUAGE_NAME).pc: bindings/c/$(LANGUAGE_NAME).pc.in
	sed -e 's|@PROJECT_VERSION@|$(VERSION)|' \
		-e 's|@CMAKE_INSTALL_LIBDIR@|$(LIBDIR:$(PREFIX)/%=%)|' \
		-e 's|@CMAKE_INSTALL_INCLUDEDIR@|$(INCLUDEDIR:$(PREFIX)/%=%)|' \
		-e 's|@PROJECT_DESCRIPTION@|$(DESCRIPTION)|' \
		-e 's|@PROJECT_HOMEPAGE_URL@|$(HOMEPAGE_URL)|' \
		-e 's|@CMAKE_INSTALL_PREFIX@|$(PREFIX)|' $< > $@

$(PARSER): $(SRC_DIR)/grammar.json
	$(TS) generate $^

install: all
	install -d '$(DESTDIR)$(INCLUDEDIR)'/tree_sitter '$(DESTDIR)$(PCLIBDIR)' '$(DESTDIR)$(LIBDIR)'
	install -m644 bindings/c/$(LANGUAGE_NAME).h '$(DESTDIR)$(INCLUDEDIR)'/tree_sitter/$(LANGUAGE_NAME).h
	install -m644 $(LANGUAGE_NAME).pc '$(DESTDIR)$(PCLIBDIR)'/$(LANGUAGE_NAME).pc
	install -m644 lib$(LANGUAGE_NAME).a '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).a
	install -m755 lib$(LANGUAGE_NAME).$(SOEXT) '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXTVER)
	ln -sf lib$(LANGUAGE_NAME).$(SOEXTVER) '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXTVER_MAJOR)
	ln -sf lib$(LANGUAGE_NAME).$(SOEXTVER_MAJOR) '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXT)

uninstall:
	$(RM) '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).a \
		'$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXTVER) \
		'$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXTVER_MAJOR) \
		'$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXT) \
		'$(DESTDIR)$(INCLUDEDIR)'/tree_sitter/$(LANGUAGE_NAME).h \
		'$(DESTDIR)$(PCLIBDIR)'/$(LANGUAGE_NAME).pc

clean:
	$(RM) $(OBJS) $(LANGUAGE_NAME).pc lib$(LANGUAGE_NAME).a lib$(LANGUAGE_NAME).$(SOEXT)

test:
	$(TS) test

.PHONY: all install uninstall clean test


================================================
FILE: Package.resolved
================================================
{
  "object": {
    "pins": [
      {
        "package": "SwiftTreeSitter",
        "repositoryURL": "https://github.com/ChimeHQ/SwiftTreeSitter",
        "state": {
          "branch": null,
          "revision": "2599e95310b3159641469d8a21baf2d3d200e61f",
          "version": "0.8.0"
        }
      }
    ]
  },
  "version": 1
}


================================================
FILE: Package.swift
================================================
// swift-tools-version:5.3
import PackageDescription

let package = Package(
    name: "TreeSitterScala",
    products: [
        .library(name: "TreeSitterScala", targets: ["TreeSitterScala"]),
    ],
    dependencies: [
        .package(url: "https://github.com/ChimeHQ/SwiftTreeSitter", from: "0.8.0"),
    ],
    targets: [
        .target(
            name: "TreeSitterScala",
            dependencies: [],
            path: ".",
            sources: [
                "src/parser.c",
                "src/scanner.c",
            ],
            resources: [
                .copy("queries")
            ],
            publicHeadersPath: "bindings/swift",
            cSettings: [.headerSearchPath("src")]
        ),
        .testTarget(
            name: "TreeSitterScalaTests",
            dependencies: [
                "SwiftTreeSitter",
                "TreeSitterScala",
            ],
            path: "bindings/swift/TreeSitterScalaTests"
        )
    ],
    cLanguageStandard: .c11
)


================================================
FILE: README.md
================================================
# tree-sitter-scala

[![CI][ci]](https://github.com/tree-sitter/tree-sitter-scala/actions/workflows/ci.yml)
[![discord][discord]](https://discord.gg/w7nTvsVJhm)
[![matrix][matrix]](https://matrix.to/#/#tree-sitter-chat:matrix.org)
[![crates][crates]](https://crates.io/crates/tree-sitter-scala)
[![npm][npm]](https://www.npmjs.com/package/tree-sitter-scala)

Scala grammar for [tree-sitter](https://github.com/tree-sitter/tree-sitter)
covering both Scala 2 and 3.

## References

_Scala 2_

- [The Scala 2 Language Specification](https://www.scala-lang.org/files/archive/spec/2.13/)
- [Scala 2 Syntax Summary](https://www.scala-lang.org/files/archive/spec/2.13/13-syntax-summary.html)

_Scala 3_

- [Scala 3 Syntax Summary](https://docs.scala-lang.org/scala3/reference/syntax.html)

## Development and Contributing

Please refer to the [CONTRIBUTING.md](./CONTRIBUTING.md) for instructions on
getting set up.

[ci]: https://img.shields.io/github/actions/workflow/status/tree-sitter/tree-sitter-scala/ci.yml?logo=github&label=CI
[discord]: https://img.shields.io/discord/1063097320771698699?logo=discord&label=discord
[matrix]: https://img.shields.io/matrix/tree-sitter-chat%3Amatrix.org?logo=matrix&label=matrix
[npm]: https://img.shields.io/npm/v/tree-sitter-scala?logo=npm
[crates]: https://img.shields.io/crates/v/tree-sitter-scala?logo=rust


================================================
FILE: binding.gyp
================================================
{
  "targets": [
    {
      "target_name": "tree_sitter_scala_binding",
      "dependencies": [
        "<!(node -p \"require('node-addon-api').targets\"):node_addon_api_except",
      ],
      "include_dirs": [
        "src",
      ],
      "sources": [
        "bindings/node/binding.cc",
        "src/parser.c",
        "src/scanner.c",
      ],
      "conditions": [
        ["OS!='win'", {
          "cflags_c": [
            "-std=c11",
          ],
        }, { # OS == "win"
          "cflags_c": [
            "/std:c11",
            "/utf-8",
          ],
        }],
      ],
    }
  ]
}


================================================
FILE: bindings/c/tree-sitter-scala.h
================================================
#ifndef TREE_SITTER_SCALA_H_
#define TREE_SITTER_SCALA_H_

typedef struct TSLanguage TSLanguage;

#ifdef __cplusplus
extern "C" {
#endif

const TSLanguage *tree_sitter_scala(void);

#ifdef __cplusplus
}
#endif

#endif // TREE_SITTER_SCALA_H_


================================================
FILE: bindings/c/tree-sitter-scala.pc.in
================================================
prefix=@CMAKE_INSTALL_PREFIX@
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@

Name: tree-sitter-scala
Description: @PROJECT_DESCRIPTION@
URL: @PROJECT_HOMEPAGE_URL@
Version: @PROJECT_VERSION@
Libs: -L${libdir} -ltree-sitter-scala
Cflags: -I${includedir}


================================================
FILE: bindings/c/tree_sitter/tree-sitter-scala.h
================================================
#ifndef TREE_SITTER_SCALA_H_
#define TREE_SITTER_SCALA_H_

typedef struct TSLanguage TSLanguage;

#ifdef __cplusplus
extern "C" {
#endif

const TSLanguage *tree_sitter_scala(void);

#ifdef __cplusplus
}
#endif

#endif // TREE_SITTER_SCALA_H_


================================================
FILE: bindings/go/binding.go
================================================
package tree_sitter_scala

// #cgo CFLAGS: -std=c11 -fPIC
// #include "../../src/parser.c"
// #include "../../src/scanner.c"
import "C"

import "unsafe"

// Get the tree-sitter Language for this grammar.
func Language() unsafe.Pointer {
	return unsafe.Pointer(C.tree_sitter_scala())
}


================================================
FILE: bindings/go/binding_test.go
================================================
package tree_sitter_scala_test

import (
	"testing"

	tree_sitter "github.com/tree-sitter/go-tree-sitter"
	tree_sitter_scala "github.com/tree-sitter/tree-sitter-scala/bindings/go"
)

func TestCanLoadGrammar(t *testing.T) {
	language := tree_sitter.NewLanguage(tree_sitter_scala.Language())
	if language == nil {
		t.Errorf("Error loading Scala grammar")
	}
}


================================================
FILE: bindings/node/binding.cc
================================================
#include <napi.h>

typedef struct TSLanguage TSLanguage;

extern "C" TSLanguage *tree_sitter_scala();

// "tree-sitter", "language" hashed with BLAKE2
const napi_type_tag LANGUAGE_TYPE_TAG = {
    0x8AF2E5212AD58ABF, 0xD5006CAD83ABBA16
};

Napi::Object Init(Napi::Env env, Napi::Object exports) {
    exports["name"] = Napi::String::New(env, "scala");
    auto language = Napi::External<TSLanguage>::New(env, tree_sitter_scala());
    language.TypeTag(&LANGUAGE_TYPE_TAG);
    exports["language"] = language;
    return exports;
}

NODE_API_MODULE(tree_sitter_scala_binding, Init)


================================================
FILE: bindings/node/binding_test.js
================================================
const assert = require("node:assert");
const { test } = require("node:test");

const Parser = require("tree-sitter");

test("can load grammar", () => {
  const parser = new Parser();
  assert.doesNotThrow(() => parser.setLanguage(require(".")));
});


================================================
FILE: bindings/node/index.d.ts
================================================
type BaseNode = {
  type: string;
  named: boolean;
};

type ChildNode = {
  multiple: boolean;
  required: boolean;
  types: BaseNode[];
};

type NodeInfo =
  | (BaseNode & {
      subtypes: BaseNode[];
    })
  | (BaseNode & {
      fields: { [name: string]: ChildNode };
      children: ChildNode[];
    });

type Language = {
  name: string;
  language: unknown;
  nodeTypeInfo: NodeInfo[];
};

declare const language: Language;
export = language;


================================================
FILE: bindings/node/index.js
================================================
const root = require("path").join(__dirname, "..", "..");

module.exports =
  typeof process.versions.bun === "string"
    // Support `bun build --compile` by being statically analyzable enough to find the .node file at build-time
    ? require(`../../prebuilds/${process.platform}-${process.arch}/tree-sitter-scala.node`)
    : require("node-gyp-build")(root);

try {
  module.exports.nodeTypeInfo = require("../../src/node-types.json");
} catch (_) {}


================================================
FILE: bindings/python/tests/test_binding.py
================================================
from unittest import TestCase

import tree_sitter, tree_sitter_scala


class TestLanguage(TestCase):
    def test_can_load_grammar(self):
        try:
            tree_sitter.Language(tree_sitter_scala.language())
        except Exception:
            self.fail("Error loading Scala grammar")


================================================
FILE: bindings/python/tree_sitter_scala/__init__.py
================================================
"""Scala grammar for tree-sitter"""

from importlib.resources import files as _files

from ._binding import language


def _get_query(name, file):
    query = _files(f"{__package__}.queries") / file
    globals()[name] = query.read_text()
    return globals()[name]


def __getattr__(name):
    if name == "HIGHLIGHTS_QUERY":
        return _get_query("HIGHLIGHTS_QUERY", "highlights.scm")
    if name == "LOCALS_QUERY":
        return _get_query("LOCALS_QUERY", "locals.scm")

    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


__all__ = [
    "language",
    "HIGHLIGHTS_QUERY",
    "LOCALS_QUERY",
]


def __dir__():
    return sorted(__all__ + [
        "__all__", "__builtins__", "__cached__", "__doc__", "__file__",
        "__loader__", "__name__", "__package__", "__path__", "__spec__",
    ])


================================================
FILE: bindings/python/tree_sitter_scala/__init__.pyi
================================================
from typing import Final

HIGHLIGHTS_QUERY: Final[str]
LOCALS_QUERY: Final[str]

def language() -> object: ...


================================================
FILE: bindings/python/tree_sitter_scala/binding.c
================================================
#include <Python.h>

typedef struct TSLanguage TSLanguage;

TSLanguage *tree_sitter_scala(void);

static PyObject* _binding_language(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(args)) {
    return PyCapsule_New(tree_sitter_scala(), "tree_sitter.Language", NULL);
}

static PyMethodDef methods[] = {
    {"language", _binding_language, METH_NOARGS,
     "Get the tree-sitter language for this grammar."},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef module = {
    .m_base = PyModuleDef_HEAD_INIT,
    .m_name = "_binding",
    .m_doc = NULL,
    .m_size = -1,
    .m_methods = methods
};

PyMODINIT_FUNC PyInit__binding(void) {
    return PyModule_Create(&module);
}


================================================
FILE: bindings/python/tree_sitter_scala/py.typed
================================================


================================================
FILE: bindings/rust/build.rs
================================================
fn main() {
    let src_dir = std::path::Path::new("src");

    let mut c_config = cc::Build::new();
    c_config
        .std("c11")
        .include(src_dir)
        .flag_if_supported("-Wno-unused");

    #[cfg(target_env = "msvc")]
    c_config.flag("-utf-8");

    let parser_path = src_dir.join("parser.c");
    c_config.file(&parser_path);
    println!("cargo:rerun-if-changed={}", parser_path.to_str().unwrap());

    let scanner_path = src_dir.join("scanner.c");
    c_config.file(&scanner_path);
    println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap());

    c_config.compile("tree-sitter-scala");
}


================================================
FILE: bindings/rust/lib.rs
================================================
//! This crate provides Scala language support for the [tree-sitter][] parsing library.
//!
//! Typically, you will use the [LANGUAGE][] constant to add this language to a
//! tree-sitter [Parser][], and then use the parser to parse some code:
//!
//! ```
//! use tree_sitter::Parser;
//!
//! let code = r#"
//! object Hello {
//!   def main(args: Array[String]) = {
//!     println("Hello, world")
//!   }
//! }
//! "#;
//! let mut parser = Parser::new();
//! let language = tree_sitter_scala::LANGUAGE;
//! parser
//!     .set_language(&language.into())
//!     .expect("Error loading Scala parser");
//! let tree = parser.parse(code, None).unwrap();
//! assert!(!tree.root_node().has_error());
//! ```
//!
//! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html
//! [tree-sitter]: https://tree-sitter.github.io/

use tree_sitter_language::LanguageFn;

extern "C" {
    fn tree_sitter_scala() -> *const ();
}

/// The tree-sitter [`LanguageFn`][LanguageFn] for this grammar.
///
/// [LanguageFn]: https://docs.rs/tree-sitter-language/*/tree_sitter_language/struct.LanguageFn.html
pub const LANGUAGE: LanguageFn = unsafe { LanguageFn::from_raw(tree_sitter_scala) };

/// The content of the [`node-types.json`][] file for this grammar.
///
/// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers#static-node-types
pub const NODE_TYPES: &str = include_str!("../../src/node-types.json");

/// The syntax highlighting query for this language.
pub const HIGHLIGHTS_QUERY: &str = include_str!("../../queries/highlights.scm");

/// The local-variable syntax highlighting query for this language.
pub const LOCALS_QUERY: &str = include_str!("../../queries/locals.scm");

#[cfg(test)]
mod tests {
    #[test]
    fn test_can_load_grammar() {
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(&super::LANGUAGE.into())
            .expect("Error loading Scala parser");
    }
}


================================================
FILE: bindings/swift/TreeSitterScala/scala.h
================================================
#ifndef TREE_SITTER_SCALA_H_
#define TREE_SITTER_SCALA_H_

typedef struct TSLanguage TSLanguage;

#ifdef __cplusplus
extern "C" {
#endif

const TSLanguage *tree_sitter_scala(void);

#ifdef __cplusplus
}
#endif

#endif // TREE_SITTER_SCALA_H_


================================================
FILE: bindings/swift/TreeSitterScalaTests/TreeSitterScalaTests.swift
================================================
import XCTest
import SwiftTreeSitter
import TreeSitterScala

final class TreeSitterScalaTests: XCTestCase {
    func testCanLoadGrammar() throws {
        let parser = Parser()
        let language = Language(language: tree_sitter_scala())
        XCTAssertNoThrow(try parser.setLanguage(language),
                         "Error loading Scala grammar")
    }
}


================================================
FILE: examples/Packages.scala
================================================
package a.b
package c {
  object A
}
package c {
  package object d {
    val hello: String = "there"
  }
}


================================================
FILE: examples/PathResolver.scala
================================================
/* NSC -- new Scala compiler
 * Copyright 2006-2013 LAMP/EPFL
 * @author  Paul Phillips
 */

package scala
package tools
package util

import java.net.URL
import scala.tools.reflect.WrappedProperties.AccessControl
import scala.tools.nsc.Settings
import scala.tools.nsc.util.ClassPath
import scala.reflect.io.{Directory, File, Path}
import PartialFunction.condOpt
import scala.tools.nsc.classpath._

// Loosely based on the draft specification at:
// https://wiki.scala-lang.org/display/SIW/Classpath

object PathResolver {
  // Imports property/environment functions which suppress security exceptions.
  import AccessControl._
  import java.lang.System.{lineSeparator => EOL}

  implicit class MkLines(val t: TraversableOnce[_]) extends AnyVal {
    def mkLines: String = t.mkString("", EOL, EOL)
    def mkLines(header: String, indented: Boolean = false, embraced: Boolean = false): String = {
      val space = "\u0020"
      val sep = if (indented) EOL + space * 2 else EOL
      val (lbrace, rbrace) = if (embraced) (space + "{", EOL + "}") else ("", "")
      t.mkString(header + lbrace + sep, sep, rbrace + EOL)
    }
  }
  implicit class AsLines(val s: String) extends AnyVal {
    // sm"""...""" could do this in one pass
    def asLines = s.trim.stripMargin.lines.mkLines
  }

  /** pretty print class path */
  def ppcp(s: String) = ClassPath.split(s) match {
    case Nil      => ""
    case Seq(x)   => x
    case xs       => xs.mkString(EOL, EOL, "")
  }

  /** Values found solely by inspecting environment or property variables.
   */
  object Environment {
    import scala.collection.JavaConverters._

    private def searchForBootClasspath =
      System.getProperties.asScala collectFirst { case (k, v) if k endsWith ".boot.class.path" => v } getOrElse ""

    /** Environment variables which java pays attention to so it
     *  seems we do as well.
     */
    def sourcePathEnv       = envOrElse("SOURCEPATH", "")

    def javaBootClassPath   = propOrElse("sun.boot.class.path", searchForBootClasspath)
    def javaExtDirs         = propOrEmpty("java.ext.dirs")
    def scalaHome           = propOrEmpty("scala.home")
    def scalaExtDirs        = propOrEmpty("scala.ext.dirs")

    /** The java classpath and whether to use it. */
    def javaUserClassPath   = propOrElse("java.class.path", "")
    def useJavaClassPath    = propOrFalse("scala.usejavacp")

    override def toString = s"""
      |object Environment {
      |  scalaHome          = $scalaHome (useJavaClassPath = $useJavaClassPath)
      |  javaBootClassPath  = <${javaBootClassPath.length} chars>
      |  javaExtDirs        = ${ppcp(javaExtDirs)}
      |  javaUserClassPath  = ${ppcp(javaUserClassPath)}
      |  scalaExtDirs       = ${ppcp(scalaExtDirs)}
      |}""".asLines
  }

  /** Default values based on those in Environment as interpreted according
   *  to the path resolution specification.
   */
  object Defaults {
    def scalaSourcePath   = Environment.sourcePathEnv
    def javaBootClassPath = Environment.javaBootClassPath
    def javaUserClassPath = Environment.javaUserClassPath
    def javaExtDirs       = Environment.javaExtDirs
    def useJavaClassPath  = Environment.useJavaClassPath

    def scalaHome         = Environment.scalaHome
    def scalaHomeDir      = Directory(scalaHome)
    def scalaLibDir       = Directory(scalaHomeDir / "lib")
    def scalaClassesDir   = Directory(scalaHomeDir / "classes")

    def scalaLibAsJar     = File(scalaLibDir / "scala-library.jar")
    def scalaLibAsDir     = Directory(scalaClassesDir / "library")

    def scalaLibDirFound: Option[Directory] =
      if (scalaLibAsJar.isFile) Some(scalaLibDir)
      else if (scalaLibAsDir.isDirectory) Some(scalaClassesDir)
      else None

    def scalaLibFound =
      if (scalaLibAsJar.isFile) scalaLibAsJar.path
      else if (scalaLibAsDir.isDirectory) scalaLibAsDir.path
      else ""

    // TODO It must be time for someone to figure out what all these things
    // are intended to do.  This is disabled here because it was causing all
    // the scala jars to end up on the classpath twice: one on the boot
    // classpath as set up by the runner (or regular classpath under -nobootcp)
    // and then again here.
    def scalaBootClassPath  = ""
    def scalaExtDirs = Environment.scalaExtDirs
    def scalaPluginPath = (scalaHomeDir / "misc" / "scala-devel" / "plugins").path

    override def toString = s"""
      |object Defaults {
      |  scalaHome            = $scalaHome
      |  javaBootClassPath    = ${ppcp(javaBootClassPath)}
      |  scalaLibDirFound     = $scalaLibDirFound
      |  scalaLibFound        = $scalaLibFound
      |  scalaBootClassPath   = ${ppcp(scalaBootClassPath)}
      |  scalaPluginPath      = ${ppcp(scalaPluginPath)}
      |}""".asLines
  }

  /** Locations discovered by supplemental heuristics.
   */
  object SupplementalLocations {

    /** The platform-specific support jar.
     *
     *  Usually this is `tools.jar` in the jdk/lib directory of the platform distribution.
     *
     *  The file location is determined by probing the lib directory under JDK_HOME or JAVA_HOME,
     *  if one of those environment variables is set, then the lib directory under java.home,
     *  and finally the lib directory under the parent of java.home. Or, as a last resort,
     *  search deeply under those locations (except for the parent of java.home, on the notion
     *  that if this is not a canonical installation, then that search would have little
     *  chance of succeeding).
     */
    def platformTools: Option[File] = {
      val jarName = "tools.jar"
      def jarPath(path: Path) = (path / "lib" / jarName).toFile
      def jarAt(path: Path) = {
        val f = jarPath(path)
        if (f.isFile) Some(f) else None
      }
      val jdkDir = {
        val d = Directory(jdkHome)
        if (d.isDirectory) Some(d) else None
      }
      def deeply(dir: Directory) = dir.deepFiles find (_.name == jarName)

      val home    = envOrSome("JDK_HOME", envOrNone("JAVA_HOME")) map (p => Path(p))
      val install = Some(Path(javaHome))

      (home flatMap jarAt) orElse (install flatMap jarAt) orElse (install map (_.parent) flatMap jarAt) orElse
        (jdkDir flatMap deeply)
    }
    override def toString = s"""
      |object SupplementalLocations {
      |  platformTools        = $platformTools
      |}""".asLines
  }

  /** With no arguments, show the interesting values in Environment and Defaults.
   *  If there are arguments, show those in Calculated as if those options had been
   *  given to a scala runner.
   */
  def main(args: Array[String]): Unit =
    if (args.isEmpty) {
      println(Environment)
      println(Defaults)
    } else {
      val settings = new Settings()
      val rest = settings.processArguments(args.toList, processAll = false)._2
      val pr = new PathResolver(settings)
      println("COMMAND: 'scala %s'".format(args.mkString(" ")))
      println("RESIDUAL: 'scala %s'\n".format(rest.mkString(" ")))

      pr.result match {
        case cp: AggregateClassPath =>
          println(s"ClassPath has ${cp.aggregates.size} entries and results in:\n${cp.asClassPathStrings}")
      }
    }
}

final class PathResolver(settings: Settings) {
  private val classPathFactory = new ClassPathFactory(settings)

  import PathResolver.{ AsLines, Defaults, ppcp }

  private def cmdLineOrElse(name: String, alt: String) = {
    (commandLineFor(name) match {
      case Some("") => None
      case x        => x
    }) getOrElse alt
  }

  private def commandLineFor(s: String): Option[String] = condOpt(s) {
    case "javabootclasspath"  => settings.javabootclasspath.value
    case "javaextdirs"        => settings.javaextdirs.value
    case "bootclasspath"      => settings.bootclasspath.value
    case "extdirs"            => settings.extdirs.value
    case "classpath" | "cp"   => settings.classpath.value
    case "sourcepath"         => settings.sourcepath.value
  }

  /** Calculated values based on any given command line options, falling back on
   *  those in Defaults.
   */
  object Calculated {
    def scalaHome           = Defaults.scalaHome
    def useJavaClassPath    = settings.usejavacp.value || Defaults.useJavaClassPath
    def useManifestClassPath= settings.usemanifestcp.value
    def javaBootClassPath   = cmdLineOrElse("javabootclasspath", Defaults.javaBootClassPath)
    def javaExtDirs         = cmdLineOrElse("javaextdirs", Defaults.javaExtDirs)
    def javaUserClassPath   = if (useJavaClassPath) Defaults.javaUserClassPath else ""
    def scalaBootClassPath  = cmdLineOrElse("bootclasspath", Defaults.scalaBootClassPath)
    def scalaExtDirs        = cmdLineOrElse("extdirs", Defaults.scalaExtDirs)

    /** Scaladoc doesn't need any bootstrapping, otherwise will create errors such as:
     * [scaladoc] ../scala-trunk/src/reflect/scala/reflect/macros/Reifiers.scala:89: error: object api is not a member of package reflect
     * [scaladoc] case class ReificationException(val pos: reflect.api.PositionApi, val msg: String) extends Throwable(msg)
     * [scaladoc]                                              ^
     * because the bootstrapping will look at the sourcepath and create package "reflect" in "<root>"
     * and then when typing relative names, instead of picking <root>.scala.relect, typedIdentifier will pick up the
     * <root>.reflect package created by the bootstrapping. Thus, no bootstrapping for scaladoc!
     * TODO: we should refactor this as a separate -bootstrap option to have a clean implementation, no? */
    def sourcePath          = if (!settings.isScaladoc) cmdLineOrElse("sourcepath", Defaults.scalaSourcePath) else ""

    def userClassPath = settings.classpath.value  // default is specified by settings and can be overridden there

    import classPathFactory._

    // Assemble the elements!
    def basis = List[Traversable[ClassPath]](
      JrtClassPath.apply(),                         // 0. The Java 9 classpath (backed by the jrt:/ virtual system, if available)
      classesInPath(javaBootClassPath),             // 1. The Java bootstrap class path.
      contentsOfDirsInPath(javaExtDirs),            // 2. The Java extension class path.
      classesInExpandedPath(javaUserClassPath),     // 3. The Java application class path.
      classesInPath(scalaBootClassPath),            // 4. The Scala boot class path.
      contentsOfDirsInPath(scalaExtDirs),           // 5. The Scala extension class path.
      classesInExpandedPath(userClassPath),         // 6. The Scala application class path.
      classesInManifest(useManifestClassPath),      // 8. The Manifest class path.
      sourcesInPath(sourcePath)                     // 7. The Scala source path.
    )

    lazy val containers = basis.flatten.distinct

    override def toString = s"""
      |object Calculated {
      |  scalaHome            = $scalaHome
      |  javaBootClassPath    = ${ppcp(javaBootClassPath)}
      |  javaExtDirs          = ${ppcp(javaExtDirs)}
      |  javaUserClassPath    = ${ppcp(javaUserClassPath)}
      |  useJavaClassPath     = $useJavaClassPath
      |  scalaBootClassPath   = ${ppcp(scalaBootClassPath)}
      |  scalaExtDirs         = ${ppcp(scalaExtDirs)}
      |  userClassPath        = ${ppcp(userClassPath)}
      |  sourcePath           = ${ppcp(sourcePath)}
      |}""".asLines
  }

  def containers = Calculated.containers

  import PathResolver.MkLines

  def result: ClassPath = {
    val cp = computeResult()
    if (settings.Ylogcp) {
      Console print f"Classpath built from ${settings.toConciseString} %n"
      Console print s"Defaults: ${PathResolver.Defaults}"
      Console print s"Calculated: $Calculated"

      val xs = (Calculated.basis drop 2).flatten.distinct
      Console print (xs mkLines (s"After java boot/extdirs classpath has ${xs.size} entries:", indented = true))
    }
    cp
  }

  def resultAsURLs: Seq[URL] = result.asURLs

  @deprecated("Use resultAsURLs instead of this one", "2.11.5")
  def asURLs: List[URL] = resultAsURLs.toList

  private def computeResult(): ClassPath = AggregateClassPath(containers.toIndexedSeq)
}


================================================
FILE: examples/RefChecks.scala
================================================
/*
 * Scala (https://www.scala-lang.org)
 *
 * Copyright EPFL and Lightbend, Inc.
 *
 * Licensed under Apache License 2.0
 * (http://www.apache.org/licenses/LICENSE-2.0).
 *
 * See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.
 */

package scala.tools.nsc
package typechecker

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.reflect.internal.util.CodeAction
import scala.tools.nsc.Reporting.WarningCategory
import scala.tools.nsc.settings.ScalaVersion
import scala.tools.nsc.settings.NoScalaVersion
import symtab.Flags._
import transform.Transform

/** Post-attribution checking and transformation.
 *
 *  This phase checks the following postconditions:
 *
 *  - All overrides conform to rules.
 *  - All type arguments conform to bounds.
 *  - Every use of a type variable conforms to the variance annotation of that variable.
 *  - No forward reference to a term symbol extends beyond a value definition.
 *
 *  It performs the following transformations:
 *
 *  - Local modules are replaced by variables and classes.
 *  - Calls to case factory methods are replaced by new's.
 *  - Eliminate branches in a conditional if the condition is a constant.
 *
 *  @author  Martin Odersky
 */
abstract class RefChecks extends Transform {

  val global: Global               // need to repeat here because otherwise last mixin defines global as
                                   // SymbolTable. If we had DOT this would not be an issue

  import global._
  import definitions._
  import typer.typed

  /** the following two members override abstract members in Transform */
  val phaseName: String = "refchecks"

  def newTransformer(unit: CompilationUnit): RefCheckTransformer =
    new RefCheckTransformer(unit)

  val toJavaRepeatedParam  = SubstSymMap(RepeatedParamClass -> JavaRepeatedParamClass)
  val toScalaRepeatedParam = SubstSymMap(JavaRepeatedParamClass -> RepeatedParamClass)

  def accessFlagsToString(sym: Symbol) = flagsToString(
    sym getFlag (PRIVATE | PROTECTED),
    if (sym.hasAccessBoundary) "" + sym.privateWithin.name else ""
  )

  def overridesTypeInPrefix(tp1: Type, tp2: Type, prefix: Type): Boolean = (tp1.dealiasWiden, tp2.dealiasWiden) match {
    case (MethodType(List(), rtp1), NullaryMethodType(rtp2)) => rtp1 <:< rtp2
    case (NullaryMethodType(rtp1), MethodType(List(), rtp2)) => rtp1 <:< rtp2
    case (TypeRef(_, sym, _), _) if sym.isModuleClass        => overridesTypeInPrefix(NullaryMethodType(tp1), tp2, prefix)
    case (_, TypeRef(_, sym, _)) if sym.isModuleClass        => overridesTypeInPrefix(tp1, NullaryMethodType(tp2), prefix)
    case _                                                   => tp1 <:< tp2
  }

  private val separatelyCompiledScalaSuperclass = perRunCaches.newAnyRefMap[Symbol, Unit]()
  final def isSeparatelyCompiledScalaSuperclass(sym: Symbol) = if (globalPhase.refChecked){
    separatelyCompiledScalaSuperclass.contains(sym)
  } else {
    // conservative approximation in case someone in pre-refchecks phase asks for `exitingFields(someClass.info)`
    // and we haven't run the refchecks tree transform which populates `separatelyCompiledScalaSuperclass`
    false
  }

  class RefCheckTransformer(unit: CompilationUnit) extends AstTransformer {
    private final val indent = "  "

    var localTyper: analyzer.Typer = typer
    var currentApplication: Tree = EmptyTree
    var inAnnotation: Boolean = false
    var inPattern: Boolean = false
    @inline final def savingInPattern[A](body: => A): A = {
      val saved = inPattern
      try body finally inPattern = saved
    }

    // Track symbols of the refinement's parents and the base at which we've checked them,
    // as well as the entire refinement type seen at that base.
    // No need to check the same symbols again in a base that's a subclass of a previously checked base
    private val checkedCombinations = mutable.Map[List[Symbol], (Symbol, Type)]()
    private def notYetCheckedOrAdd(rt: RefinedType, currentBase: Symbol) = {
      val seen = checkedCombinations.get(rt.parents.map(_.typeSymbol)).exists {
        case (prevBase, prevTp) => currentBase.isSubClass(prevBase) && rt =:= prevTp.asSeenFrom(currentBase.thisType, prevBase)
      }

      if (!seen) checkedCombinations.addOne((rt.parents.map(_.typeSymbol), (currentBase, rt)))

      !seen
    }

    private def refchecksWarning(pos: Position, msg: String, cat: WarningCategory, actions: List[CodeAction] = Nil): Unit =
      runReporting.warning(pos, msg, cat, currentOwner, actions)

    // only one overloaded alternative is allowed to define default arguments
    private def checkOverloadedRestrictions(clazz: Symbol, defaultClass: Symbol): Unit = {
      // Using the default getters (such as methodName$default$1) as a cheap way of
      // finding methods with default parameters. This way, we can limit the members to
      // those with the DEFAULTPARAM flag, and infer the methods. Looking for the methods
      // directly requires inspecting the parameter list of every one. That modification
      // shaved 95% off the time spent in this method.
      val defaultGetters     = defaultClass.info.findMembers(excludedFlags = PARAM, requiredFlags = DEFAULTPARAM)
      val defaultMethodNames = defaultGetters map (sym => nme.defaultGetterToMethod(sym.name))

      defaultMethodNames.toList.distinct foreach { name =>
        val methods      = clazz.info.findMember(name, 0L, requiredFlags = METHOD, stableOnly = false).alternatives
        def hasDefaultParam(tpe: Type): Boolean = tpe match {
          case MethodType(params, restpe) => (params exists (_.hasDefault)) || hasDefaultParam(restpe)
          case _                          => false
        }
        val haveDefaults = methods.filter(sym => mexists(sym.info.paramss)(_.hasDefault) && !nme.isProtectedAccessorName(sym.name))

        if (haveDefaults.lengthCompare(1) > 0) {
          val owners = haveDefaults map (_.owner)
           // constructors of different classes are allowed to have defaults
          if (haveDefaults.exists(x => !x.isConstructor) || owners.distinct.size < haveDefaults.size) {
            reporter.error(clazz.pos,
              "in "+ clazz +
              ", multiple overloaded alternatives of "+ haveDefaults.head +
              " define default arguments" + (
                if (owners.forall(_ == clazz)) "."
                else ".\nThe members with defaults are defined in "+owners.map(_.fullLocationString).mkString("", " and ", ".")
              )
            )
          }
        }
      }

      // Check for doomed attempt to overload applyDynamic
      if (clazz isSubClass DynamicClass) {
        for ((_, m1 :: m2 :: _) <- (clazz.info member nme.applyDynamic).alternatives groupBy (_.typeParams.length)) {
          reporter.error(m1.pos, "implementation restriction: applyDynamic cannot be overloaded except by methods with different numbers of type parameters, e.g. applyDynamic[T1](method: String)(arg: T1) and applyDynamic[T1, T2](method: String)(arg1: T1, arg2: T2)")
        }
      }

      // This has become noisy with implicit classes.
      if (settings.isDeveloper && settings.warnPolyImplicitOverload) {
        clazz.info.decls.foreach(sym => if (sym.isImplicit && sym.typeParams.nonEmpty) {
          // implicit classes leave both a module symbol and a method symbol as residue
          val alts = clazz.info.decl(sym.name).alternatives filterNot (_.isModule)
          if (alts.size > 1)
            alts foreach (x => refchecksWarning(x.pos, "parameterized overloaded implicit methods are not visible as view bounds", WarningCategory.LintPolyImplicitOverload))
        })
      }
    }

// Override checking ------------------------------------------------------------

    /** Add bridges for vararg methods that extend Java vararg methods
     */
    def addVarargBridges(clazz: Symbol): List[Tree] = {
      // This is quite expensive, so attempt to skip it completely.
      // Insist there at least be a java-defined ancestor which
      // defines a varargs method. TODO: Find a cheaper way to exclude.
      if (inheritsJavaVarArgsMethod(clazz)) {
        log("Found java varargs ancestor in " + clazz.fullLocationString + ".")
        val self = clazz.thisType
        val bridges = new ListBuffer[Tree]

        def varargBridge(member: Symbol, bridgetpe: Type): Tree = {
          log(s"Generating varargs bridge for ${member.fullLocationString} of type $bridgetpe")

          val newFlags = (member.flags | VBRIDGE) & ~PRIVATE
          val bridge   = member.cloneSymbolImpl(clazz, newFlags) setPos clazz.pos
          bridge.setInfo(bridgetpe.cloneInfo(bridge))
          clazz.info.decls enter bridge

          val params  = bridge.paramss.head
          val elemtp  = params.last.tpe.typeArgs.head
          val idents  = params map Ident
          val lastarg = gen.wildcardStar(gen.mkWrapVarargsArray(idents.last, elemtp))
          val body    = Apply(Select(This(clazz), member), idents.init :+ lastarg)

          localTyper typed DefDef(bridge, body)
        }

        // For all concrete non-private members (but: see below) that have a (Scala) repeated
        //   parameter: compute the corresponding method type `jtpe` with a Java repeated parameter
        //   if a method with type `jtpe` exists and that method is not a varargs bridge
        //   then create a varargs bridge of type `jtpe` that forwards to the
        //   member method with the Scala vararg type.
        //
        // @PP: Can't call nonPrivateMembers because we will miss refinement members,
        //   which have been marked private. See scala/bug#4729.
        for (member <- nonTrivialMembers(clazz)) {
          log(s"Considering $member for java varargs bridge in $clazz")
          if (!member.isDeferred && member.isMethod && hasRepeatedParam(member.info)) {
            val inherited = clazz.info.nonPrivateMemberAdmitting(member.name, VBRIDGE)

            // Delaying calling memberType as long as possible
            if (inherited.exists) {
              val jtpe = toJavaRepeatedParam(self memberType member)
              // this is a bit tortuous: we look for non-private members or bridges
              // if we find a bridge everything is OK. If we find another member,
              // we need to create a bridge
              val inherited1 = inherited filter (sym => !(sym hasFlag VBRIDGE) && (self memberType sym matches jtpe))
              if (inherited1.exists)
                bridges += varargBridge(member, jtpe)
            }
          }
        }

        if (bridges.size > 0)
          log(s"Adding ${bridges.size} bridges for methods extending java varargs.")

        bridges.toList
      }
      else Nil
    }

    /** 1. Check all members of class `clazz` for overriding conditions.
     *  That is for overriding member M and overridden member O:
     *
     *    1.1. M must have the same or stronger access privileges as O.
     *    1.2. O must not be final.
     *    1.3. O is deferred, or M has `override` modifier.
     *    1.4. If O is stable, then so is M.
     *    1.6. If O is a type alias, then M is an alias of O.
     *    1.7. If O is an abstract type then
     *       1.7.1 either M is an abstract type, and M's bounds are sharper than O's bounds.
     *             or M is a type alias or class which conforms to O's bounds.
     *       1.7.2 higher-order type arguments must respect bounds on higher-order type parameters  -- @M
     *              (explicit bounds and those implied by variance annotations) -- @see checkKindBounds
     *    1.8. If O and M are values, then
     *    1.8.1  M's type is a subtype of O's type, or
     *    1.8.2  M is of type []S, O is of type ()T and S <: T, or
     *    1.8.3  M is of type ()S, O is of type []T and S <: T, or
     *    1.9.  If M is a macro def, O cannot be deferred unless there's a concrete method overriding O.
     *    1.10. If M is not a macro def, O cannot be a macro def.
     *  2. Check that only abstract classes have deferred members
     *  3. Check that concrete classes do not have deferred definitions
     *     that are not implemented in a subclass.
     *  4. Check that every member with an `override` modifier
     *     overrides some other member.
     *  5. Check that the nested class do not shadow other nested classes from outer class's parent.
     */
    private def checkAllOverrides(clazz: Symbol, typesOnly: Boolean = false): Unit = {
      val self = clazz.thisType

      case class MixinOverrideError(member: Symbol, msg: String, actions: List[CodeAction], s3Migration: Boolean)

      val mixinOverrideErrors = new ListBuffer[MixinOverrideError]()

      def issue(pos: Position, msg: String, actions: List[CodeAction], s3Migration: Boolean) =
        if (s3Migration) runReporting.warning(pos, msg, WarningCategory.Scala3Migration, currentOwner, actions)
        else runReporting.error(pos, msg, actions)

      def printMixinOverrideErrors(): Unit = {
        mixinOverrideErrors.toList match {
          case List() =>
          case List(MixinOverrideError(_, msg, actions, s3Migration)) =>
            issue(clazz.pos, msg, actions, s3Migration)
          case MixinOverrideError(member, msg, actions, s3Migration) :: others =>
            val others1 = others.map(_.member.name.decode).filter(member.name.decode != _).distinct
            issue(
              clazz.pos,
              if (others1.isEmpty) msg
              else s"$msg;\n other members with override errors are: ${others1.mkString(", ")}",
              actions,
              s3Migration)
        }
      }

      def infoString(sym: Symbol) = infoString0(sym, sym.owner != clazz)
      def infoStringWithLocation(sym: Symbol) = infoString0(sym, showLocation = true)

      def infoString0(member: Symbol, showLocation: Boolean) = {
        val location =
          if (!showLocation) ""
          else member.ownsString match {
            case ""   => ""
            case s    => s" (defined in $s)"
          }
        val macroStr = if (member.isTermMacro) "macro " else ""

        macroStr + member.defStringSeenAs(self.memberInfo(member)) + location
      }

      /* Check that all conditions for overriding `other` by `member` of class `clazz` are met.
       *
       * TODO: error messages could really be improved, including how they are composed
       */
      def checkOverride(pair: SymbolPair): Unit = {
        import pair.{highType, lowType, highInfo, rootType}

        val member = pair.low
        val other = pair.high
        val memberClass = member.owner
        val otherClass = other.owner

        // debuglog(s"Checking validity of ${member.fullLocationString} overriding ${other.fullLocationString}")

        def noErrorType = !pair.isErroneous
        def isRootOrNone(sym: Symbol) = sym != null && sym.isRoot || sym == NoSymbol
        val isMemberClass = memberClass == clazz
        def isNeitherInClass = !isMemberClass && otherClass != clazz

        /** Emit an error if member is owned by current class, using the member position.
         *  Otherwise, accumulate the error, to be emitted after other messages, using the class position.
         */
        def emitOverrideError(fullmsg: String, actions: List[CodeAction] = Nil, s3Migration: Boolean = false): Unit =
          if (isMemberClass) issue(member.pos, fullmsg, actions, s3Migration)
          else mixinOverrideErrors += MixinOverrideError(member, fullmsg, actions, s3Migration)

        def overriddenWithAddendum(msg: String, foundReq: Boolean = settings.isDebug): String = {
          val isConcreteOverAbstract =
            otherClass.isSubClass(memberClass) && other.isDeferred && !member.isDeferred
          val addendum =
            if (isConcreteOverAbstract)
              sm"""|;
                   |${indent}(note that ${infoStringWithLocation(other)} is abstract,
                   |${indent}and is therefore overridden by concrete ${infoStringWithLocation(member)})"""
            else if (foundReq) {
              def info(sym: Symbol) = self.memberInfo(sym) match { case tp if sym.isGetter || sym.isValue && !sym.isMethod => tp.resultType case tp => tp }
              analyzer.foundReqMsg(info(member), info(other))
            }
            else ""
          val msg1 = if (!msg.isEmpty) s"\n$indent$msg" else msg

          s"${infoStringWithLocation(other)}${msg1}${addendum}"
        }

        def overrideError(msg: String): Unit =
          if (noErrorType) emitOverrideError(msg)

        def getWithIt = if (isMemberClass) "" else s"with ${infoString(member)}"

        def overrideErrorWithMemberInfo(msg: String, actions: List[CodeAction] = Nil, s3Migration: Boolean = false): Unit =
          if (noErrorType) emitOverrideError(s"${msg}\n${overriddenWithAddendum(getWithIt)}", actions, s3Migration)

        def overrideErrorOrNullaryWarning(msg: String, actions: List[CodeAction]): Unit = if (isMemberClass || !member.owner.isSubClass(other.owner))
          if (currentRun.isScala3)
            overrideErrorWithMemberInfo(msg, actions, s3Migration = true)
          else if (isMemberClass)
            refchecksWarning(member.pos, msg, WarningCategory.OtherNullaryOverride, actions)
          else
            refchecksWarning(clazz.pos, msg, WarningCategory.OtherNullaryOverride, actions)

        def overrideTypeError(): Unit =
          if (member.isModule && other.isModule)
            overrideError(sm"""|overriding ${other.fullLocationString} with ${member.fullLocationString}:
                               |an overriding object must conform to the overridden object's class bound${
                                analyzer.foundReqMsg(pair.lowClassBound, pair.highClassBound)}""")
          else {
            val needSameType = !other.isDeferred && other.isAliasType
            val msg = s"${getWithIt}${if (needSameType) " (Equivalent type required when overriding a type alias.)" else ""}"
            overrideError(sm"""|incompatible type in overriding
                               |${overriddenWithAddendum(msg, foundReq = !needSameType)}""")
          }

        def overrideErrorConcreteMissingOverride() =
          if (isNeitherInClass && !otherClass.isSubClass(memberClass))
            emitOverrideError(sm"""|$clazz inherits conflicting members:
                                   |$indent${infoStringWithLocation(other)} and
                                   |$indent${infoStringWithLocation(member)}
                                   |$indent(note: this can be resolved by declaring an `override` in $clazz.)""")
          else
            overrideErrorWithMemberInfo("`override` modifier required to override concrete member:")

        def weakerAccessError(advice: String): Unit =
          overrideError(sm"""|weaker access privileges in overriding
                             |${overriddenWithAddendum(advice)}""")
        def overrideAccessError(): Unit =
          weakerAccessError {
            accessFlagsToString(other) match {
              case ""          => "override should be public"
              case otherAccess => s"override should at least be $otherAccess"
            }
          }

        //Console.println(infoString(member) + " overrides " + infoString(other) + " in " + clazz);//DEBUG

        /* Is the intersection between given two lists of overridden symbols empty? */
        def intersectionIsEmpty(syms1: List[Symbol], syms2: List[Symbol]) = !syms1.exists(syms2.contains)

        if (memberClass == ObjectClass && otherClass == AnyClass) () // skip -- can we have a mode of symbolpairs where this pair doesn't even appear?
        else if (typesOnly) checkOverrideTypes()
        else {
          // o: public | protected        | package-protected  (aka java's default access)
          // ^-may be overridden by member with access privileges-v
          // m: public | public/protected | public/protected/package-protected-in-same-package-as-o

          if (member.isPrivate) // (1.1)
            weakerAccessError("override should not be private")

          // todo: align accessibility implication checking with isAccessible in Contexts
          @inline def protectedOK = !other.isProtected || member.isProtected
          @inline def accessBoundaryOK = {
            val ob = other.accessBoundary(memberClass)
            val mb = member.accessBoundary(memberClass)
            @inline def companionBoundaryOK = ob.isClass && mb.isModuleClass && mb.module == ob.companionSymbol
            !isRootOrNone(ob) && (ob.hasTransOwner(mb) || companionBoundaryOK)
          }
          @inline def otherIsJavaProtected = other.isJavaDefined && other.isProtected
          val isOverrideAccessOK =
            member.isPublic ||     // member is public, definitely same or relaxed access
            protectedOK &&         // if o is protected, so is m
            (accessBoundaryOK ||   // m relaxes o's access boundary
              otherIsJavaProtected // overriding a protected java member, see #3946 #12349
            )
          if (!isOverrideAccessOK)
            overrideAccessError()
          else if (other.isClass)
            overrideErrorWithMemberInfo("class definitions cannot be overridden:")
          else if (!other.isDeferred && member.isClass)
            overrideErrorWithMemberInfo("classes can only override abstract types; cannot override:")
          else if (other.isEffectivelyFinal) // (1.2)
            overrideErrorWithMemberInfo("cannot override final member:")
          else {
            // In Java, the OVERRIDE flag is implied
            val memberOverrides = member.isAnyOverride || (member.isJavaDefined && !member.isDeferred)

            // Concrete `other` requires `override` for `member`.
            // Synthetic exclusion for (at least) default getters, fixes scala/bug#5178.
            // We cannot assign the OVERRIDE flag to the default getter:
            // one default getter might sometimes override, sometimes not. Example in comment on ticket.
            if (!memberOverrides && !other.isDeferred && !member.isSynthetic)
              overrideErrorConcreteMissingOverride()
            else if (other.isAbstractOverride && other.isIncompleteIn(clazz) && !member.isAbstractOverride)
              overrideErrorWithMemberInfo("`abstract override` modifiers required to override:")
            else if (memberOverrides && other.hasFlag(ACCESSOR) && !other.hasFlag(STABLE | DEFERRED))
              // TODO: this is not covered by the spec.
              overrideErrorWithMemberInfo("mutable variable cannot be overridden:")
            else if (memberOverrides &&
                     !memberClass.thisType.baseClasses.exists(_.isSubClass(otherClass)) &&
                     !member.isDeferred && !other.isDeferred &&
                     intersectionIsEmpty(member.extendedOverriddenSymbols, other.extendedOverriddenSymbols))
              overrideErrorWithMemberInfo("cannot override a concrete member without a third member that's overridden by both " +
                                          "(this rule is designed to prevent accidental overrides)")
            else if (other.isStable && !member.isStable) // (1.4)
              overrideErrorWithMemberInfo("stable, immutable value required to override:")
            else if (member.isValue && member.isLazy &&
                       other.isValue && other.hasStableFlag && !other.isDeferred && !other.isLazy)
              overrideErrorWithMemberInfo("concrete non-lazy value cannot be overridden:")
            else if (other.isValue && other.isLazy && member.isValue && !member.isLazy)
              overrideErrorWithMemberInfo("value must be lazy when overriding concrete lazy value:")
            else if (other.isDeferred && member.isTermMacro && member.extendedOverriddenSymbols.forall(_.isDeferred)) // (1.9)
              overrideErrorWithMemberInfo("macro cannot override abstract method:")
            else if (other.isTermMacro && !member.isTermMacro) // (1.10)
              overrideErrorWithMemberInfo("macro can only be overridden by another macro:")
            else {
              checkOverrideTypes()
              // Don't bother users with deprecations caused by classes they inherit.
              // Only warn for the pair that has one leg in `clazz`.
              if (isMemberClass) checkOverrideDeprecated()
              def javaDetermined(sym: Symbol) = sym.isJavaDefined || isUniversalMember(sym)
              def exempted = javaDetermined(member) || javaDetermined(other) || member.overrides.exists(javaDetermined)
              // warn that nilary member matched nullary other, so either it was adapted by namer or will be silently mixed in by mixin
              def warnAdaptedNullaryOverride(): Unit = {
                val mbr = if (isMemberClass) "method" else s"${member.fullLocationString} defined"
                val msg = s"$mbr without a parameter list overrides ${other.fullLocationString} defined with a single empty parameter list"
                val namePos = member.pos
                val action =
                  if (namePos.isDefined && namePos.source.sourceAt(namePos) == member.decodedName)
                    runReporting.codeAction("add empty parameter list", namePos.focusEnd, "()", msg)
                  else Nil
                overrideErrorOrNullaryWarning(msg, action)
              }
              def warnExtraParens(): Unit = {
                val mbr = if (isMemberClass) "method" else s"${member.fullLocationString} defined"
                val msg = s"$mbr with a single empty parameter list overrides ${other.fullLocationString} defined without a parameter list"
                val namePos = member.pos
                val action =
                  if (namePos.isDefined && namePos.source.sourceAt(namePos) == member.decodedName)
                    runReporting.codeAction("remove empty parameter list", namePos.focusEnd.withEnd(namePos.end + 2), "", msg, expected = Some(("()", currentUnit)))
                  else Nil
                overrideErrorOrNullaryWarning(msg, action)
              }
              if (member.hasAttachment[NullaryOverrideAdapted.type]) {
                if (!exempted)
                  warnAdaptedNullaryOverride()
              }
              else if (member.paramLists.isEmpty) {
                // Definitions that directly override get a parameter list and a `NullaryOverrideAdapted` attachment
                // in Namers. Here we also warn when there's a mismatch between two mixed-in members.
                if (!member.isStable && other.paramLists.nonEmpty && !exempted && !other.overrides.exists(javaDetermined))
                  warnAdaptedNullaryOverride()
              }
              else if (other.paramLists.isEmpty) {
                if (!exempted && !member.hasAnnotation(BeanPropertyAttr) && !member.hasAnnotation(BooleanBeanPropertyAttr))
                  warnExtraParens()
              }
            }
          }
        }

        def checkOverrideAlias(): Unit = {
          // Important: first check the pair has the same kind, since the substitution
          // carries high's type parameter's bounds over to low, so that
          // type equality doesn't consider potentially different bounds on low/high's type params.
          // In b781e25afe this went from using memberInfo to memberType (now lowType/highType), tested by neg/override.scala.
          // TODO: was that the right fix? it seems type alias's RHS should be checked by looking at the symbol's info
          if (pair.sameKind && lowType.substSym(member.typeParams, other.typeParams) =:= highType) ()
          else overrideTypeError() // (1.6)
        }
        def checkOverrideAbstractType(): Unit = {
          if (!(highInfo.bounds containsType lowType)) { // (1.7.1)
            overrideTypeError(); // todo: do an explaintypes with bounds here
            explainTypes(_.bounds containsType _, highInfo, lowType)
          }
          // check overriding (abstract type --> abstract type or abstract type --> concrete type member (a type alias))
          // making an abstract type member concrete is like passing a type argument
          typer.infer.checkKindBounds(other :: Nil, lowType :: Nil, rootType, memberClass) match { // (1.7.2)
            case Nil        =>
            case kindErrors =>
              reporter.error(member.pos,
                "The kind of " + member.keyString+" " + member.varianceString + member.nameString+
                " does not conform to the expected kind of " + other.defString + other.locationString + "." +
                kindErrors.toList.mkString("\n", ", ", ""))
          }
          // check a type alias's RHS corresponds to its declaration
          // this overlaps somewhat with validateVariance
          if (member.isAliasType) {
            typer.infer.checkKindBounds(member :: Nil, lowType.normalize :: Nil, rootType, memberClass) match {
              case Nil        =>
              case kindErrors =>
                reporter.error(member.pos,
                  "The kind of the right-hand side "+lowType.normalize+" of " + member.keyString+" "+
                  member.varianceString + member.nameString+ " does not conform to its expected kind."+
                  kindErrors.toList.mkString("\n", ", ", ""))
            }
          }
          else if (member.isAbstractType && lowType.isVolatile && !highInfo.upperBound.isVolatile)
            overrideErrorWithMemberInfo("volatile type member cannot override type member with non-volatile upper bound:")
        }
        def checkOverrideTerm(): Unit = {
          member.cookJavaRawInfo() // #11584, #11840
          other.cookJavaRawInfo() // #2454
          if (!overridesTypeInPrefix(lowType, highType, rootType)) { // 8
            overrideTypeError()
            explainTypes(lowType, highType)
          }
          if (member.isStable && !highType.isVolatile) {
            if (lowType.isVolatile)
              overrideErrorWithMemberInfo("member with volatile type cannot override member with non-volatile type:")
            else lowType.normalize.resultType match {
              case rt: RefinedType if !(rt =:= highType) && notYetCheckedOrAdd(rt, pair.base) =>
                // might mask some inconsistencies -- check overrides
                val tsym = rt.typeSymbol
                if (tsym.pos == NoPosition) tsym setPos member.pos
                checkAllOverrides(tsym, typesOnly = true)
              case _ =>
            }
          }
        }
        def checkOverrideTypes(): Unit = {
          if (other.isAliasType)         checkOverrideAlias()
          else if (other.isAbstractType) checkOverrideAbstractType()
          else if (other.isTerm)         checkOverrideTerm()
        }

        def checkOverrideDeprecated(): Unit = {
          if (other.hasDeprecatedOverridingAnnotation && !(member.hasDeprecatedOverridingAnnotation || member.ownerChain.exists(_.isDeprecated))) {
            val version = other.deprecatedOverridingVersion.getOrElse("")
            val since   = if (version.isEmpty) version else s" (since $version)"
            val message = other.deprecatedOverridingMessage map (msg => s": $msg") getOrElse ""
            val report  = s"overriding ${other.fullLocationString} is deprecated$since$message"
            runReporting.deprecationWarning(member.pos, other, member, report, version)
          }
        }
      }

      val opc = new overridingPairs.PairsCursor(clazz)
      while (opc.hasNext) {
        if (!opc.high.isClass)
          checkOverride(opc.currentPair)

        opc.next()
      }
      printMixinOverrideErrors()

      // Verifying a concrete class has nothing unimplemented.
      if (clazz.isConcreteClass && !typesOnly) {
        val abstractErrors = ListBuffer.empty[String]
        def abstractErrorMessage = abstractErrors.mkString("\n")

        def abstractClassError(msg: String, supplement: String = "", mustBeMixin: Boolean = false): Unit = {
          def prelude =
            if (clazz.isAnonymousClass || clazz.isModuleClass) "object creation impossible."
            else if (mustBeMixin) s"$clazz needs to be a mixin."
            else s"$clazz needs to be abstract."

          if (abstractErrors.isEmpty) abstractErrors += prelude
          abstractErrors += msg
          if (!supplement.isEmpty) abstractErrors += supplement
        }

        def javaErasedOverridingSym(sym: Symbol): Symbol =
          clazz.tpe.nonPrivateMemberAdmitting(sym.name, BRIDGE).filter(other =>
            !other.isDeferred && other.isJavaDefined && !sym.enclClass.isSubClass(other.enclClass) && {
              // #3622: erasure operates on uncurried types --
              // note on passing sym in both cases: only sym.isType is relevant for uncurry.transformInfo
              // !!! erasure.erasure(sym, uncurry.transformInfo(sym, tp)) gives erroneous or inaccessible type - check whether that's still the case!
              def uncurryAndErase(tp: Type) = erasure.erasure(sym)(uncurry.transformInfo(sym, tp))
              val tp1 = uncurryAndErase(clazz.thisType.memberType(sym))
              val tp2 = uncurryAndErase(clazz.thisType.memberType(other))
              exitingErasure(tp1 matches tp2)
            })

        def ignoreDeferred(member: Symbol) =
          (member.isAbstractType && !member.isFBounded) || (
            // the test requires exitingErasure so shouldn't be
            // done if the compiler has no erasure phase available
               member.isJavaDefined
            && (currentRun.erasurePhase == NoPhase || javaErasedOverridingSym(member) != NoSymbol)
          )

        // 2. Check that only abstract classes have deferred members
        def checkNoAbstractMembers(): Unit = {
          val NoError = null.asInstanceOf[String]
          val EmptyDiagnostic = ""
          def diagnose(member: Symbol, accessors: List[Symbol], nonPrivateMembers: Scope, fastDiagnostics: Boolean): String = {
            val underlying = analyzer.underlyingSymbol(member) // TODO: don't use this method

            // Give a specific error message for abstract vars based on why it fails:
            // It could be unimplemented, have only one accessor, or be uninitialized.
            val isMultiple = accessors.size > 1

            if (accessors.exists(_.isSetter) || (member.isGetter && !isMultiple && member.setterIn(member.owner).exists)) {
              if (member.isSetter && isMultiple) NoError // If both getter and setter are missing, squelch the setter error.
              else if (member.isSetter) "an abstract var requires a setter in addition to the getter"
              else if (member.isGetter && !isMultiple) "an abstract var requires a getter in addition to the setter"
              else "variables need to be initialized to be defined"
            }
            else if (!fastDiagnostics && underlying.isMethod) {
              // Highlight any member that nearly matches: same name and arity,
              // but differs in one param or param list.
              val abstractParamLists = underlying.paramLists
              val matchingArity      = nonPrivateMembers.reverseIterator.filter { m =>
                !m.isDeferred &&
                m.name == underlying.name &&
                sameLength(m.paramLists, abstractParamLists) &&
                sumSize(m.paramLists, 0) == sumSize(abstractParamLists, 0) &&
                sameLength(m.tpe.typeParams, underlying.tpe.typeParams) &&
                !(m.isJavaDefined && m.hasFlag(JAVA_DEFAULTMETHOD))
              }.toList
              matchingArity match {
                // So far so good: only one candidate method
                case concrete :: Nil =>
                  val concreteParamLists = concrete.paramLists
                  val aplIter = abstractParamLists.iterator.flatten
                  val cplIter = concreteParamLists.iterator.flatten
                  def mismatch(apl: Symbol, cpl: Symbol): Option[(Type, Type)] =
                    if (apl.tpe.asSeenFrom(clazz.tpe, underlying.owner) =:= cpl.tpe) None else Some(apl.tpe -> cpl.tpe)
                  def missingImplicit = abstractParamLists.zip(concreteParamLists).exists {
                    case (abss, konkrete) => abss.headOption.exists(_.isImplicit) && !konkrete.headOption.exists(_.isImplicit)
                  }
                  val mismatches = mapFilter2(aplIter, cplIter)(mismatch).take(2).toList
                  mismatches match {
                    // Only one mismatched parameter: say something useful.
                    case (pa, pc) :: Nil  =>
                      val abstractSym = pa.typeSymbol
                      val concreteSym = pc.typeSymbol
                      def subclassMsg(c1: Symbol, c2: Symbol) =
                        s": ${c1.fullLocationString} is a subclass of ${c2.fullLocationString}, but method parameter types must match exactly."
                      def wrongSig = {
                        val m = concrete
                        fullyInitializeSymbol(m)
                        m.defStringSeenAs(clazz.tpe_*.memberType(m))
                      }
                      val addendum =
                        if (abstractSym == concreteSym) {
                          if (underlying.isJavaDefined && pa.typeArgs.isEmpty && abstractSym.typeParams.nonEmpty)
                            s". To implement this raw type, use ${rawToExistential(pa)}"
                          else if (pa.prefix =:= pc.prefix)
                            ": their type parameters differ"
                          else
                            ": their prefixes (i.e., enclosing instances) differ"
                        }
                        else if (abstractSym.isSubClass(concreteSym)) subclassMsg(abstractSym, concreteSym)
                        else if (concreteSym.isSubClass(abstractSym)) subclassMsg(concreteSym, abstractSym)
                        else s" in `$wrongSig`"
                      s"$pa does not match $pc$addendum"
                    case Nil if missingImplicit => "overriding member must declare implicit parameter list" // other overriding gotchas
                    case _ => EmptyDiagnostic
                  }
                case _ => EmptyDiagnostic
              }
            }
            else EmptyDiagnostic
          }
          def emitErrors(missing: List[Symbol], nonPrivateMembers: Scope): Unit = {
            val fastDiagnostics = missing.lengthCompare(100) > 0
            // Group missing members by the name of the underlying symbol, to consolidate getters and setters.
            val byName = missing.groupBy(_.name.getterName)
            // There may be 1 or more missing members declared in 1 or more parents.
            // If a single parent, the message names it. Otherwise, missing members are grouped by declaring class.
            val byOwner = missing.groupBy(_.owner).toList
            val announceOwner = byOwner.size > 1
            def membersStrings(members: List[Symbol]) = {
              members.sortBy(_.name).flatMap { m =>
                val accessors = byName.getOrElse(m.name.getterName, Nil)
                val diagnostic = diagnose(m, accessors, nonPrivateMembers, fastDiagnostics)
                if (diagnostic == NoError) Nil
                else {
                  val s0a = infoString0(m, showLocation = false)
                  fullyInitializeSymbol(m)
                  val s0b = m.defString
                  val s1 = m.defStringSeenAs(clazz.tpe_*.memberType(m))
                  val implMsg = if (s1 != s0a) s"implements `$s0a`" else if (s1 != s0b) s"implements `$s0b`" else ""
                  val spacer  = if (diagnostic.nonEmpty && implMsg.nonEmpty) "; " else ""
                  val comment = if (diagnostic.nonEmpty || implMsg.nonEmpty) s" // $implMsg$spacer$diagnostic" else ""
                  s"$s1 = ???$comment" :: Nil
                }
              }
            }
            var count = 0
            def isMulti = count > 1
            def helpfulListing =
              byOwner.sortBy(_._1.name.toString).flatMap {
                case (owner, members) =>
                  val ms = membersStrings(members) :+ ""
                  count += ms.size - 1
                  if (announceOwner) s"// Members declared in ${owner.fullName}" :: ms else ms
              }.init.map(s => s"  $s\n").mkString
            val stubs = helpfulListing
            def singleParent = if (byOwner.size == 1 && byOwner.head._1 != clazz) s" member${if (isMulti) "s" else ""} of ${byOwner.head._1}" else ""
            val line0 =
              if (isMulti) s"Missing implementations for ${count}${val p = singleParent ; if (p.isEmpty) " members" else p}."
              else s"Missing implementation${val p = singleParent ; if (p.isEmpty) p else s" for$p"}:"
            abstractClassError(line0, supplement = stubs)
          }
          def filtered[A](it: Iterator[A])(p: A => Boolean)(q: A => Boolean): (List[A], List[A]) = {
            var ps, qs: List[A] = Nil
            while (it.hasNext) {
              val a = it.next()
              if (p(a)) ps ::= a
              else if (q(a)) qs ::= a
            }
            (ps, qs)
          }
          val nonPrivateMembers = clazz.info.nonPrivateMembersAdmitting(VBRIDGE)
          // Avoid extra allocations with reverseIterator. Filter for abstract members of interest, and bad abstract override.
          val (missing, abstractIncomplete): (List[Symbol], List[Symbol]) =
            filtered(nonPrivateMembers.reverseIterator)(m => m.isDeferred & !ignoreDeferred(m))(m => m.isAbstractOverride && m.isIncompleteIn(clazz))
          if (missing.nonEmpty) emitErrors(missing, nonPrivateMembers)
          // Check the remainder for invalid absoverride.
          for (member <- abstractIncomplete) {
            val explanation = member.superSymbolIn(clazz) match {
              case NoSymbol => ", but no concrete implementation could be found in a base class"
              case other    => " and overrides incomplete superclass member\n" + infoString(other)
            }
            abstractClassError(s"${infoString(member)} is marked `abstract` and `override`$explanation", mustBeMixin = true)
          }
        } // end checkNoAbstractMembers

        // 3. Check that concrete classes do not have deferred definitions
        // that are not implemented in a subclass.
        // Note that this is not the same as (2); In a situation like
        //
        // class C { def m: Int = 0}
        // class D extends C { def m: Int }
        //
        // (3) is violated but not (2).
        def checkNoAbstractDecls(bc: Symbol): Unit = {
          for (decl <- bc.info.decls) {
            if (decl.isDeferred && !ignoreDeferred(decl)) {
              val impl = decl.matchingSymbol(clazz.thisType, admit = VBRIDGE)
              if (impl == NoSymbol || decl.owner.isSubClass(impl.owner))
                abstractClassError(s"No implementation found in a subclass for deferred declaration\n" +
                                          s"${infoString(decl)}${analyzer.abstractVarMessage(decl)}")
            }
          }
          if (bc.superClass hasFlag ABSTRACT)
            checkNoAbstractDecls(bc.superClass)
        }

        checkNoAbstractMembers()
        if (abstractErrors.isEmpty)
          checkNoAbstractDecls(clazz)

        if (abstractErrors.nonEmpty)
          reporter.error(clazz.pos, abstractErrorMessage)
      }
      else if (clazz.isTrait && !clazz.isSubClass(AnyValClass)) {
        // For non-AnyVal classes, prevent abstract methods in interfaces that override
        // final members in Object; see #4431
        for (decl <- clazz.info.decls) {
          // Have to use matchingSymbol, not a method involving overridden symbols,
          // because the scala type system understands that an abstract method here does not
          // override a concrete method in Object. The jvm, however, does not.
          val overridden = decl.matchingSymbol(ObjectClass, ObjectTpe)
          if (overridden.isFinal)
            reporter.error(decl.pos, "trait cannot redefine final method from class AnyRef")
        }
      }

      /* Returns whether there is a symbol declared in class `inclazz`
       * (which must be different from `clazz`) whose name and type
       * seen as a member of `class.thisType` matches `member`'s.
       */
      def hasMatchingSym(inclazz: Symbol, member: Symbol): Boolean = {
        val isVarargs = hasRepeatedParam(member.tpe)
        lazy val varargsType = toJavaRepeatedParam(member.tpe)

        def isSignatureMatch(sym: Symbol) = !sym.isTerm || {
          val symtpe = clazz.thisType.memberType(sym)
          member.tpe.matches(symtpe) || (isVarargs && varargsType.matches(symtpe))
        }
        /* The rules for accessing members which have an access boundary are more
         * restrictive in java than scala.  Since java has no concept of package nesting,
         * a member with "default" (package-level) access can only be accessed by members
         * in the exact same package.  Example:
         *
         *   package a.b;
         *   public class JavaClass { void foo() { } }
         *
         * The member foo() can be accessed only from members of package a.b, and not
         * nested packages like a.b.c.  In the analogous scala class:
         *
         *   package a.b
         *   class ScalaClass { private[b] def foo() = () }
         *
         * The member IS accessible to classes in package a.b.c.  The javaAccessCheck logic
         * is restricting the set of matching signatures according to the above semantics.
         */
        def javaAccessCheck(sym: Symbol) = (
             !inclazz.isJavaDefined                             // not a java defined member
          || !sym.hasAccessBoundary                             // no access boundary
          || sym.isProtected                                    // marked protected in java, thus accessible to subclasses
          || sym.privateWithin == member.enclosingPackageClass  // exact package match
        )
        def classDecl = inclazz.info.nonPrivateDecl(member.name)
                        .orElse(inclazz.info.nonPrivateDecl(member.unexpandedName))
        def matchingSyms = classDecl.filter(sym => isSignatureMatch(sym) && javaAccessCheck(sym))

        (inclazz != clazz) && (matchingSyms != NoSymbol)
      }

      // 4. Check that every defined member with an `override` modifier overrides some other member.
      for (member <- clazz.info.decls)
        if (member.isAnyOverride && !clazz.thisType.baseClasses.exists(hasMatchingSym(_, member))) {
          // for (bc <- clazz.info.baseClasses.tail) Console.println("" + bc + " has " + bc.info.decl(member.name) + ":" + bc.info.decl(member.name).tpe);//DEBUG

          val nonMatching: List[Symbol] = clazz.info.member(member.name).alternatives.filterNot(_.owner == clazz).filterNot(_.isFinal)
          def issueError(suffix: String) = reporter.error(member.pos, member.toString() + " overrides nothing" + suffix)
          nonMatching match {
            case Nil =>
              issueError("")
            case ms =>
              val superSigs = ms.map(m => m.defStringSeenAs(clazz.tpe memberType m)).mkString("\n")
              issueError(s".\nNote: the super classes of ${member.owner} contain the following, non final members named ${member.name}:\n${superSigs}")
          }
          member resetFlag (OVERRIDE | ABSOVERRIDE)  // Any Override
        }

      // 5. Check that the nested class do not shadow other nested classes from outer class's parent
      def checkNestedClassShadow(): Unit =
        if (clazz.isNestedClass && !clazz.isModuleClass) {
          val overridden = clazz.owner.ancestors
            .map(a => clazz.matchingSymbol(a, clazz.owner.thisType))
            .filter(c => c.exists && c.isClass)
          overridden foreach { sym2 =>
            def msg(what: String) = s"shadowing a nested class of a parent is $what but $clazz shadows $sym2 defined in ${sym2.owner}; rename the class to something else"
            if (currentRun.isScala3) runReporting.warning(clazz.pos, msg("deprecated"), WarningCategory.Scala3Migration, clazz)
            else runReporting.deprecationWarning(clazz.pos, clazz, currentOwner, msg("deprecated"), "2.13.2")
          }
        }
      checkNestedClassShadow()
    } // end checkAllOverrides

  // Basetype Checking --------------------------------------------------------

    /** <ol>
     *    <li> <!-- 1 -->
     *      Check that later type instances in the base-type sequence
     *      are subtypes of earlier type instances of the same mixin.
     *    </li>
     *  </ol>
     */
    private def validateBaseTypes(clazz: Symbol): Unit = {
      val seenParents = mutable.HashSet[Type]()
      val seenTypes = Array.fill[List[Type]](clazz.info.baseTypeSeq.length)(Nil)
      val warnCloneable = settings.warnCloneableObject && clazz.isModuleClass

      /* validate all base types of a class in reverse linear order. */
      def register(tp: Type): Unit = {
        val baseClass = tp.typeSymbol
        if (baseClass.isClass) {
          if (!baseClass.isTrait && !baseClass.isJavaDefined && !currentRun.compiles(baseClass) && !separatelyCompiledScalaSuperclass.contains(baseClass))
            separatelyCompiledScalaSuperclass.update(baseClass, ())
          val index = clazz.info.baseTypeIndex(baseClass)
          if (index >= 0) {
            if (!seenTypes(index).exists(_ <:< tp))
              seenTypes(index) = tp :: seenTypes(index).filterNot(tp <:< _)
          }
        }
        if (warnCloneable && baseClass.eq(JavaCloneableClass))
          reporter.warning(clazz.pos, s"$clazz should not extend Cloneable.")
        val remaining = tp.parents.filterNot(seenParents)
        seenParents ++= remaining
        remaining.foreach(register)
      }
      register(clazz.tpe)
      for (i <- 0 until seenTypes.length) {
        val baseClass = clazz.info.baseTypeSeq(i).typeSymbol
        seenTypes(i) match {
          case Nil =>
            devWarning(s"base $baseClass not found in basetypes of $clazz. This might indicate incorrect caching of TypeRef#parents.")
          case _ :: Nil => // OK
          case tp1 :: tp2 :: _ =>
            reporter.error(clazz.pos,
              sm"""|illegal inheritance;
                   | $clazz inherits different type instances of $baseClass:
                   |$tp1 and $tp2""")
            explainTypes(tp1, tp2)
            explainTypes(tp2, tp1)
        }
      }
    }

  // Variance Checking --------------------------------------------------------

    object varianceValidator extends VarianceValidator {
      private def tpString(tp: Type) = tp match {
        case ClassInfoType(parents, _, clazz) => "supertype "+intersectionType(parents, clazz.owner)
        case _                                => "type "+tp
      }
      override def issueVarianceError(base: Symbol, sym: Symbol, required: Variance, tpe: Type): Unit = {
        reporter.error(base.pos,
          s"${sym.variance} $sym occurs in $required position in ${tpString(tpe)} of $base")
      }
    }

// Forward reference checking ---------------------------------------------------

    class LevelInfo(val outer: LevelInfo) {
      val scope: Scope = if (outer eq null) newScope else newNestedScope(outer.scope)
      var maxindex: Int = Int.MinValue
      var refpos: Position = _
      var refsym: Symbol = _
    }

    private var currentLevel: LevelInfo = null
    private val symIndex = perRunCaches.newMap[Symbol, Int]()

    private def pushLevel(): Unit = {
      currentLevel = new LevelInfo(currentLevel)
    }

    private def popLevel(): Unit = {
      currentLevel = currentLevel.outer
    }

    private def enterSyms(stats: List[Tree]): Unit = {
      var index = -1
      for (stat <- stats) {
        index = index + 1

        stat match {
          case _ : MemberDef if stat.symbol.isLocalToBlock =>
            currentLevel.scope.enter(stat.symbol)
            symIndex(stat.symbol) = index
          case _ =>
        }
      }
    }

    private def enterReference(pos: Position, sym: Symbol): Unit = {
      if (sym.isLocalToBlock) {
        val e = currentLevel.scope.lookupEntry(sym.name)
        if ((e ne null) && sym == e.sym) {
          var l = currentLevel
          while (l.scope != e.owner) l = l.outer
          val symindex = symIndex(sym)
          if (l.maxindex < symindex) {
            l.refpos = pos
            l.refsym = sym
            l.maxindex = symindex
          }
        }
      }
    }

// Comparison checking -------------------------------------------------------
    object normalizeAll extends TypeMap {
      def apply(tp: Type) = mapOver(tp).normalize
    }

    def checkImplicitViewOptionApply(pos: Position, fn: Tree, args: List[Tree]): Unit = if (settings.warnOptionImplicit) (fn, args) match {
      case (tap@TypeApply(fun, targs), List(view: ApplyImplicitView)) if fun.symbol == currentRun.runDefinitions.Option_apply =>
        refchecksWarning(pos, s"Suspicious application of an implicit view (${view.fun}) in the argument to Option.apply.", WarningCategory.LintOptionImplicit) // scala/bug#6567
      case _ =>
    }

    private def isObjectOrAnyComparisonMethod(sym: Symbol) = sym match {
      case Object_eq | Object_ne | Object_== | Object_!= | Any_== | Any_!= => true
      case _                                                               => false
    }

    /**
      * Check the sensibility of using the given `equals` to compare `qual` and `other`.
      *
      * NOTE: I'm really not convinced by the logic here. I also think this would work better after erasure.
      */
    private def checkSensibleEquals(pos: Position, qual: Tree, name: Name, sym: Symbol, other: Tree) = {
      def isReferenceOp = sym == Object_eq || sym == Object_ne
      def isNew(tree: Tree) = tree match {
        case Function(_, _) | Apply(Select(New(_), nme.CONSTRUCTOR), _) => true
        case _ => false
      }
      def underlyingClass(tp: Type): Symbol = {
        val sym = tp.widen.typeSymbol
        if (sym.isAbstractType) underlyingClass(sym.info.upperBound)
        else sym
      }
      val actual   = underlyingClass(other.tpe)
      val receiver = underlyingClass(qual.tpe)
      def onTrees[T](f: List[Tree] => T) = f(List(qual, other))
      def onSyms[T](f: List[Symbol] => T) = f(List(receiver, actual))

      // @MAT normalize for consistency in error message, otherwise only part is normalized due to use of `typeSymbol`
      def typesString = s"${normalizeAll(qual.tpe.widen)} and ${normalizeAll(other.tpe.widen)}"

      // TODO: this should probably be used in more type comparisons in checkSensibleEquals
      def erasedClass(tp: Type) = erasure.javaErasure(tp).typeSymbol

      /* Symbols which limit the warnings we can issue since they may be value types */
      val couldBeAnything = Set[Symbol](ObjectClass, ComparableClass, SerializableClass)
      def isMaybeValue(sym: Symbol): Boolean = couldBeAnything(erasedClass(sym.tpe))

      // Whether def equals(other: Any) has known behavior: it is the default
      // inherited from java.lang.Object, or it is a synthetically generated
      // case equals.  TODO - more cases are warnable if the target is a synthetic
      // equals.
      def isUsingWarnableEquals = {
        val m = receiver.info.member(nme.equals_)
        ((m == Object_equals) || (m == Any_equals) || isMethodCaseEquals(m))
      }
      def isMethodCaseEquals(m: Symbol) = m.isSynthetic && m.owner.isCase
      def isCaseEquals = isMethodCaseEquals(receiver.info.member(nme.equals_))
      // Whether this == or != is one of those defined in Any/AnyRef or an overload from elsewhere.
      def isUsingDefaultScalaOp = sym == Object_== || sym == Object_!= || sym == Any_== || sym == Any_!=
      def haveSubclassRelationship = (actual isSubClass receiver) || (receiver isSubClass actual)

      // Whether the operands+operator represent a warnable combo (assuming anyrefs)
      // Looking for comparisons performed with ==/!= in combination with either an
      // equals method inherited from Object or a case class synthetic equals (for
      // which we know the logic.)
      def isWarnable           = isReferenceOp || (isUsingDefaultScalaOp && isUsingWarnableEquals)
      def isEitherNullable     = (NullTpe <:< receiver.info) || (NullTpe <:< actual.info)
      def isEitherValueClass   = actual.isDerivedValueClass || receiver.isDerivedValueClass
      def isBoolean(s: Symbol) = unboxedValueClass(s) == BooleanClass
      def isUnit(s: Symbol)    = unboxedValueClass(s) == UnitClass
      def isNumeric(s: Symbol) = isNumericValueClass(unboxedValueClass(s)) || isAnyNumber(s)
      def isScalaNumber(s: Symbol) = s isSubClass ScalaNumberClass
      def isJavaNumber(s: Symbol)  = s isSubClass JavaNumberClass
      // includes java.lang.Number if appropriate [scala/bug#5779]
      def isAnyNumber(s: Symbol)     = isScalaNumber(s) || isJavaNumber(s)
      def isMaybeAnyValue(s: Symbol) = isPrimitiveValueClass(unboxedValueClass(s)) || isMaybeValue(s)
      // used to short-circuit unrelatedTypes check if both sides are special
      def isSpecial(s: Symbol) = isMaybeAnyValue(s) || isAnyNumber(s)
      val nullCount            = onSyms(_.filter(_ == NullClass).size)
      def isNonsenseValueClassCompare = (
           !haveSubclassRelationship
        && isUsingDefaultScalaOp
        && isEitherValueClass
        && !isCaseEquals
      )

      def isEffectivelyFinalDeep(sym: Symbol): Boolean = (
        sym.isEffectivelyFinal
        // If a parent of an intersection is final, the resulting type must effectively be final.
        // (Any subclass of the refinement would have to be a subclass of that final parent.)
        // OPT: this condition is not included in the standard isEffectivelyFinal check, as it's expensive
        || sym.isRefinementClass && sym.info.parents.exists { _.typeSymbol.isEffectivelyFinal }
      )

      // Have we already determined that the comparison is non-sensible? I mean, non-sensical?
      var isNonSensible = false

      def nonSensibleWarning(what: String, alwaysEqual: Boolean) = {
        val msg = alwaysEqual == (name == nme.EQ || name == nme.eq)
        refchecksWarning(pos, s"comparing $what using `${name.decode}` will always yield $msg", WarningCategory.Other)
        isNonSensible = true
      }
      def nonSensible(pre: String, alwaysEqual: Boolean) =
        nonSensibleWarning(s"${pre}values of types $typesString", alwaysEqual)
      def nonSensiblyEq() = nonSensible("", alwaysEqual = true)
      def nonSensiblyNeq() = nonSensible("", alwaysEqual = false)
      def nonSensiblyNew() = nonSensibleWarning("a fresh object", alwaysEqual = false)

      def unrelatedMsg = name match {
        case nme.EQ | nme.eq => "never compare equal"
        case _               => "always compare unequal"
      }
      def unrelatedTypes() = if (!isNonSensible) {
        val weaselWord = if (isEitherValueClass) "" else " most likely"
        refchecksWarning(pos, s"$typesString are unrelated: they will$weaselWord $unrelatedMsg", WarningCategory.Other)
      }

      if (nullCount == 2) // null == null
        nonSensiblyEq()
      else if (nullCount == 1) {
        if (onSyms(_ exists isPrimitiveValueClass)) // null == 5
          nonSensiblyNeq()
        else if (onTrees( _ exists isNew)) // null == new AnyRef
          nonSensiblyNew()
      }
      else if (isBoolean(receiver)) {
        if (!isBoolean(actual) && !isMaybeValue(actual))    // true == 5
          nonSensiblyNeq()
      }
      else if (isUnit(receiver)) {
        if (isUnit(actual)) // () == ()
          nonSensiblyEq()
        else if (!isUnit(actual) && !isMaybeValue(actual))  // () == "abc"
          nonSensiblyNeq()
      }
      else if (isNumeric(receiver)) {
        if (!isNumeric(actual))
          if (isUnit(actual) || isBoolean(actual) || !isMaybeValue(actual))   // 5 == "abc"
            nonSensiblyNeq()
      }
      else if (isWarnable && !isCaseEquals) {
        if (isNew(qual)) // new X == y
          nonSensiblyNew()
        else if (isNew(other) && (isEffectivelyFinalDeep(receiver) || isReferenceOp))   // object X ; X == new Y
          nonSensiblyNew()
        else if (isEffectivelyFinalDeep(actual) && isEffectivelyFinalDeep(receiver) && !haveSubclassRelationship) {  // object X, Y; X == Y
          if (isEitherNullable)
            nonSensible("non-null ", alwaysEqual = false)
          else
            nonSensiblyNeq()
        }
      }

      // warn if one but not the other is a derived value class
      // this is especially important to enable transitioning from
      // regular to value classes without silent failures.
      if (isNonsenseValueClassCompare)
        unrelatedTypes()
      // possibleNumericCount is insufficient or this will warn on e.g. Boolean == j.l.Boolean
      else if (isWarnable && nullCount == 0 && !(isSpecial(receiver) && isSpecial(actual))) {
        // Warn if types are unrelated, without interesting lub. (Don't bother if we don't know anything about the values we're comparing.)
        def warnIfLubless(): Unit = {
          if (isMaybeValue(actual) || isMaybeValue(receiver) || haveSubclassRelationship) {} // ignore trivial or related types
          else {
            // better to have lubbed and lost
            // We erase the lub because the erased type is closer to what happens at run time.
            // Also, the lub of `S` and `String` is, weirdly, the refined type `Serializable{}` (for `class S extends Serializable`),
            // which means we can't just take its type symbol and look it up in our isMaybeValue Set.
            val commonRuntimeClass = erasedClass(global.lub(List(actual.tpe, receiver.tpe)))
            if (commonRuntimeClass == ObjectClass)
              unrelatedTypes()
          }
        }

        // warn if actual has a case parent that is not same as receiver's;
        // if actual is not a case, then warn if no common supertype, as below
        if (isCaseEquals) {
          def thisCase = receiver.info.member(nme.equals_).owner
          actual.info.baseClasses.find(_.isCase) match {
            case Some(p) if p != thisCase => nonSensible("case class ", alwaysEqual = false)
            case None =>
              // stronger message on (Some(1) == None)
              //if (receiver.isCase && receiver.isEffectivelyFinal && !(receiver isSubClass actual)) nonSensiblyNeq()
              //else
              // if a class, it must be super to thisCase (and receiver) since not <: thisCase
              if (!actual.isTrait && !(receiver isSubClass actual)) nonSensiblyNeq()
              else warnIfLubless()
            case _ =>
          }
        }
        else warnIfLubless()
      }
    }

    private def checkSensibleAnyEquals(pos: Position, qual: Tree, name: Name, sym: Symbol, other: Tree) = {
      def underlyingClass(tp: Type): Symbol = {
        val sym = tp.widen.typeSymbol
        if (sym.isAbstractType) underlyingClass(sym.info.upperBound)
        else sym
      }
      val receiver = underlyingClass(qual.tpe)
      val actual   = underlyingClass(other.tpe)
      def typesString = "" + normalizeAll(qual.tpe.widen) + " and " + normalizeAll(other.tpe.widen)
      def nonSensiblyEquals() = {
        refchecksWarning(pos, s"comparing values of types $typesString using `${name.decode}` unsafely bypasses cooperative equality; use `==` instead", WarningCategory.OtherNonCooperativeEquals)
      }
      def isScalaNumber(s: Symbol) = s isSubClass ScalaNumberClass
      def isJavaNumber(s: Symbol)  = s isSubClass JavaNumberClass
      def isAnyNumber(s: Symbol)   = isScalaNumber(s) || isJavaNumber(s)
      def isNumeric(s: Symbol)     = isNumericValueClass(unboxedValueClass(s)) || isAnyNumber(s)
      def isReference(s: Symbol)   = (unboxedValueClass(s) isSubClass AnyRefClass) || (s isSubClass ObjectClass)
      def isUnit(s: Symbol)        = unboxedValueClass(s) == UnitClass
      def isNumOrNonRef(s: Symbol) = isNumeric(s) || (!isReference(s) && !isUnit(s))
      if (isNumeric(receiver) && isNumOrNonRef(actual)) {
        if (receiver == actual) ()
        else nonSensiblyEquals()
      }
      else if ((sym == Any_equals || sym == Object_equals) && isNumOrNonRef(actual) && !isReference(receiver)) {
        nonSensiblyEquals()
      }
    }

    /** Sensibility check examines flavors of equals. */
    def checkSensible(pos: Position, fn: Tree, args: List[Tree]) = fn match {
      case Select(qual, name @ (nme.EQ | nme.NE | nme.eq | nme.ne)) if args.length == 1 && isObjectOrAnyComparisonMethod(fn.symbol) && (!currentOwner.isSynthetic || currentOwner.isAnonymousFunction) =>
        checkSensibleEquals(pos, qual, name, fn.symbol, args.head)
      case Select(qual, name @ nme.equals_) if args.length == 1 && (!currentOwner.isSynthetic || currentOwner.isAnonymousFunction) =>
        checkSensibleAnyEquals(pos, qual, name, fn.symbol, args.head)
      case _ =>
    }

    // scala/bug#6276 warn for trivial recursion, such as `def foo = foo` or `val bar: X = bar`, which come up more frequently than you might think.
    // TODO: Move to abide rule. Also, this does not check that the def is final or not overridden, for example
    def checkInfiniteLoop(sym: Symbol, rhs: Tree): Unit =
      if (!sym.isValueParameter && sym.paramss.forall(_.isEmpty)) {
        rhs match {
          case Ident(_) | Select(This(_), _) | Apply(Select(This(_), _), _) if rhs hasSymbolWhich (_.accessedOrSelf == sym) =>
            refchecksWarning(rhs.pos, s"${sym.fullLocationString} does nothing other than call itself recursively", WarningCategory.Other)
          case _ =>
        }
      }

// Transformation ------------------------------------------------------------

    /* Convert a reference to a case factory of type `tpe` to a new of the class it produces. */
    def toConstructor(pos: Position, tpe: Type): Tree = {
      val rtpe = tpe.finalResultType
      assert(rtpe.typeSymbol hasFlag CASE, tpe)
      val tree = localTyper.typedOperator {
        atPos(pos) {
          Select(New(TypeTree(rtpe)), rtpe.typeSymbol.primaryConstructor)
        }
      }
      checkUndesiredProperties(rtpe.typeSymbol, tree.pos)
      checkUndesiredProperties(rtpe.typeSymbol.primaryConstructor, tree.pos)
      tree
    }

    override def transformStats(stats: List[Tree], exprOwner: Symbol): List[Tree] = {
      pushLevel()
      try {
        enterSyms(stats)
        var index = -1
        stats.mapConserve(stat => {
          index += 1;
          transformStat(stat, index)
        }).filter(_ ne EmptyTree)
      }
      finally popLevel()
    }

    private def showCurrentRef: String = {
      val refsym = currentLevel.refsym
      s"$refsym defined on line ${refsym.pos.line}"
    }

    def transformStat(tree: Tree, index: Int): Tree = tree match {
      case t if treeInfo.isSelfConstrCall(t) =>
        assert(index == 0, index)
        try transform(tree)
        finally if (currentLevel.maxindex > 0) {
          // An implementation restriction to avoid VerifyErrors and lazy vals mishaps; see scala/bug#4717
          reporter.error(currentLevel.refpos, s"forward reference to $showCurrentRef not allowed from self constructor invocation")
        }
      case ValDef(_, _, _, _) =>
        val tree1 = transform(tree) // important to do before forward reference check
        if (tree1.symbol.isLazy) tree1
        else {
          val sym = tree.symbol
          if (sym.isLocalToBlock && index <= currentLevel.maxindex) {
            reporter.error(currentLevel.refpos, s"forward reference to $showCurrentRef extends over definition of $sym")
          }
          tree1
        }
      case Import(_, _)                                                                       => EmptyTree
      case DefDef(mods, _, _, _, _, _) if (mods hasFlag MACRO) || (tree.symbol hasFlag MACRO) => EmptyTree
      case _                                                                                  => transform(tree)
    }

    /* Check whether argument types conform to bounds of type parameters */
    private def checkBounds(tree0: Tree, pre: Type, owner: Symbol, tparams: List[Symbol], argtps: List[Type]): Unit =
      try typer.infer.checkBounds(tree0, pre, owner, tparams, argtps, "")
      catch {
        case ex: TypeError =>
          reporter.error(tree0.pos, ex.getMessage())
          if (settings.explaintypes.value) {
            val bounds = tparams map (tp => tp.info.instantiateTypeParams(tparams, argtps).bounds)
            foreach2(argtps, bounds)((targ, bound) => explainTypes(bound.lo, targ))
            foreach2(argtps, bounds)((targ, bound) => explainTypes(targ, bound.hi))
          }
      }
    private def isIrrefutable(pat: Tree, seltpe: Type): Boolean = pat match {
      case Apply(_, args) =>
        val clazz = pat.tpe.typeSymbol
        clazz == seltpe.typeSymbol &&
        clazz.isCaseClass &&
        (args corresponds clazz.primaryConstructor.tpe.asSeenFrom(seltpe, clazz).paramTypes)(isIrrefutable)
      case Typed(pat, tpt) =>
        seltpe <:< tpt.tpe
      case Ident(tpnme.WILDCARD) =>
        true
      case Bind(_, pat) =>
        isIrrefutable(pat, seltpe)
      case _ =>
        false
    }

    // Note: if a symbol has both @deprecated and @migration annotations and both
    // warnings are enabled, only the first one checked here will be emitted.
    // I assume that's a consequence of some code trying to avoid noise by suppressing
    // warnings after the first, but I think it'd be better if we didn't have to
    // arbitrarily choose one as more important than the other.
    private def checkUndesiredProperties(sym: Symbol, pos: Position): Unit = {
      // Issue a warning if symbol is deprecated, unless the point of reference is enclosed by a deprecated member,
      // or has a deprecated companion.
      if (sym.isDeprecated &&
          // synthetic calls to deprecated case class constructor
          !(sym.isConstructor && sym.owner.isCaseClass && currentOwner.isSynthetic) &&
          !currentOwner.ownersIterator.exists(_.isDeprecated))
        runReporting.deprecationWarning(pos, sym, currentOwner)

      // Similar to deprecation: check if the symbol is marked with @migration
      // indicating it has changed semantics between versions.
      if (sym.hasMigrationAnnotation && settings.Xmigration.value != NoScalaVersion) {
        val changed = try
          settings.Xmigration.value < ScalaVersion(sym.migrationVersion.get)
        catch {
          case e : NumberFormatException =>
            refchecksWarning(pos, s"${sym.fullLocationString} has an unparsable version number: ${e.getMessage()}", WarningCategory.Other)
            // if we can't parse the format on the migration annotation just conservatively assume it changed
            true
        }
        if (changed)
          refchecksWarning(pos, s"${sym.fullLocationString} has changed semantics in version ${sym.migrationVersion.get}:\n${sym.migrationMessage.get}", WarningCategory.OtherMigration)
      }
      if (sym.isExperimental && !currentOwner.ownerChain.exists(x => x.isExperimental)) {
        val msg =
          s"${sym.fullLocationString} is marked @experimental and therefore its enclosing scope must be experimental."
        reporter.error(pos, msg)
      }
      // See an explanation of compileTimeOnly in its scaladoc at scala.annotation.compileTimeOnly.
      // async/await is expanded after erasure
      if (sym.isCompileTimeOnly && !inAnnotation && !currentOwner.ownerChain.exists(x => x.isCompileTimeOnly)) {
        if (!async.deferCompileTimeOnlyError(sym)) {
          def defaultMsg =
            sm"""Reference to ${sym.fullLocationString} should not have survived past type checking,
                |it should have been processed and eliminated during expansion of an enclosing macro."""
          // The getOrElse part should never happen, it's just here as a backstop.
          val msg = sym.compileTimeOnlyMessage getOrElse defaultMsg
          reporter.error(pos, msg)
        }
      }
    }

    private def checkDelayedInitSelect(qual: Tree, sym: Symbol, pos: Position) = {
      def isLikelyUninitialized = (
           (sym.owner isSubClass DelayedInitClass)
        && !qual.tpe.isInstanceOf[ThisType]
        && sym.accessedOrSelf.isVal
      )
      if (settings.warnDelayedInit && isLikelyUninitialized)
        refchecksWarning(pos, s"Selecting ${sym} from ${sym.owner}, which extends scala.DelayedInit, is likely to yield an uninitialized value", WarningCategory.LintDelayedinitSelect)
    }

    private def lessAccessible(otherSym: Symbol, memberSym: Symbol): Boolean = (
         (otherSym != NoSymbol)
      && !otherSym.isProtected
      && !otherSym.isTypeParameterOrSkolem
      && !otherSym.isExistentiallyBound
      && memberSym.ownersIterator.forall(otherSym.isLessAccessibleThan(_))
    )
    private def lessAccessibleSymsInType(other: Type, memberSym: Symbol): List[Symbol] = {
      val extras = other match {
        case TypeRef(pre, _, args) =>
          // checking the prefix here gives us spurious errors on e.g. a private[process]
          // object which contains a type alias, which normalizes to a visible type.
          args.filterNot(_ eq NoPrefix).flatMap(lessAccessibleSymsInType(_, memberSym))
        case _ =>
          Nil
      }
      if (lessAccessible(other.typeSymbol, memberSym)) other.typeSymbol :: extras
      else extras
    }
    private def warnLessAccessible(otherSym: Symbol, memberSym: Symbol): Unit = {
      val comparison = accessFlagsToString(memberSym) match {
        case ""   => ""
        case acc  => " is " + acc + " but"
      }
      val cannot =
        if (memberSym.isDeferred) "may be unable to provide a concrete implementation of"
        else "may be unable to override"

      refchecksWarning(memberSym.pos,
        s"""|${memberSym.fullLocationString}${comparison} references ${accessFlagsToString(otherSym)} ${otherSym}.
            |Classes which cannot access ${otherSym.decodedName} ${cannot} ${memberSym.decodedName}.""".stripMargin,
        WarningCategory.LintInaccessible
      )
    }

    /** Warn about situations where a method signature will include a type which
     *  has more restrictive access than the method itself.
     */
    private def checkAccessibilityOfReferencedTypes(tree: Tree): Unit = {
      val member = tree.symbol

      def checkAccessibilityOfType(tpe: Type): Unit = {
        val inaccessible = lessAccessibleSymsInType(tpe, member)
        // if the unnormalized type is accessible, that's good enough
        if (inaccessible.isEmpty) ()
        // or if the normalized type is, that's good too
        else if ((tpe ne tpe.normalize) && lessAccessibleSymsInType(tpe.dealiasWiden, member).isEmpty) ()
        // otherwise warn about the inaccessible syms in the unnormalized type
        else inaccessible.foreach(warnLessAccessible(_, member))
      }

      // types of the value parameters
      foreachParamss(member)(p => checkAccessibilityOfType(p.tpe))
      // upper bounds of type parameters
      member.typeParams.foreach(tp => checkAccessibilityOfType(tp.info.upperBound.widen))
    }

    /** Check that a deprecated val or def does not override a
      * concrete, non-deprecated method.  If it does, then
      * deprecation is meaningless.
      */
    private def checkDeprecatedOvers(tree: Tree): Unit = {
      val symbol = tree.symbol
      if (symbol.isDeprecated) {
        val concrOvers =
          symbol.allOverriddenSymbols.filter(sym =>
            !sym.isDeprecated && !sym.isDeferred && !sym.hasDeprecatedOverridingAnnotation && !sym.enclClass.hasDeprecatedInheritanceAnnotation)
        if(!concrOvers.isEmpty)
          runReporting.deprecationWarning(
            tree.pos,
            symbol,
            currentOwner,
            s"${symbol.toString} overrides concrete, non-deprecated symbol(s):    ${concrOvers.map(_.name.decode).mkString(", ")}", "")
      }
    }
    private def checkRepeatedParamArg(tree: Tree): Unit = {
      val bailure = "such annotations are only allowed in arguments to *-parameters"
      val err = currentApplication match {
        case Apply(fn, args) =>
          val ok = (    args.nonEmpty
                    && (args.last eq tree)
                    && (fn.tpe.params.length == args.length)
                    &&  isRepeatedParamType(fn.tpe.params.last.tpe)
                   )
          if (ok) null
          else if (!args.exists(tree.eq)) bailure
          else {
            val i = args.indexWhere(tree.eq)
            val isLast = i == args.length - 1
            val formal = if (i >= fn.tpe.params.length - 1) fn.tpe.params.last.tpe else fn.tpe.params(i).tpe
            val isRepeated = isRepeatedParamType(formal)
            val lastly = if (!isLast) ";\nsequence argument must be the last argument" else ""
            val solely = if (fn.tpe.params.length == 1) "single" else "corresponding"
            if (isRepeated)
              s"it is not the only argument to be passed to the $solely repeated parameter $formal$lastly"
            else
              s"the $solely parameter has type $formal which is not a repeated parameter type$lastly"
          }
        case _ => bailure
      }
      if (err != null)
        reporter.error(tree.pos, s"Sequence argument type annotation `: _*` cannot be used here:\n$err")
    }

    private object RefCheckTypeMap extends TypeMap {
      object UnboundExistential extends TypeMap {
        private[this] val bound = mutable.Set.empty[Symbol]

        def toWildcardIn(tpe: Type): Type =
          try apply(tpe) finally bound.clear()

        override def apply(tpe: Type): Type = tpe match {
          case ExistentialType(quantified, _) =>
            bound ++= quantified
            tpe.mapOver(this)
          case tpe =>
            val sym = tpe.typeSymbol
            if (sym.isExistential && !bound(sym)) WildcardType
            else tpe.mapOver(this)
        }
      }

      private[this] var inPattern = false
      private[this] var skipBounds = false
      private[this] var tree: Tree = EmptyTree

      def check(tpe: Type, tree: Tree, inPattern: Boolean = false): Type = {
        this.inPattern = inPattern
        this.tree = tree
        try apply(tpe) finally {
          this.inPattern = false
          this.skipBounds = false
          this.tree = EmptyTree
        }
      }

      // check all bounds, except those that are existential type parameters
      // or those within typed annotated with @uncheckedBounds
      override def apply(tpe: Type): Type = tpe match {
        case tpe: AnnotatedType if tpe.hasAnnotation(UncheckedBoundsClass) =>
          // scala/bug#7694 Allow code synthesizers to disable checking of bounds for TypeTrees based on inferred LUBs
          // which might not conform to the constraints.
          val savedSkipBounds = skipBounds
          skipBounds = true
          try tpe.mapOver(this).filterAnnotations(_.symbol != UncheckedBoundsClass)
          finally skipBounds = savedSkipBounds
        case tpe: TypeRef =>
          if (!inPattern) checkTypeRef(UnboundExistential.toWildcardIn(tpe))
          checkUndesired(tpe.sym)
          tpe.mapOver(this)
        case tpe =>
          tpe.mapOver(this)
      }

      private def checkTypeRef(tpe: Type): Unit = tpe match {
        case TypeRef(pre, sym, args) =>
          if (sym.isJavaDefined)
            sym.typeParams.foreach(_.cookJavaRawInfo())
          if (!tpe.isHigherKinded && !skipBounds)
            checkBounds(tree, pre, sym.owner, sym.typeParams, args)
        case _ =>
      }

      private def checkUndesired(sym: Symbol): Unit = tree match {
        // scala/bug#7783 don't warn about inferred types
        // FIXME: reconcile this check with one in resetAttrs
        case tree: TypeTree if tree.original == null =>
        case tree => checkUndesiredProperties(sym, tree.pos)
      }
    }

    private def applyRefchecksToAnnotations(tree: Tree): Unit = {
      def checkVarArgs(tp: Type, tree: Tree): Unit = tp match {
        case TypeRef(_, VarargsClass, _) =>
          tree match {
            case tt: TypeTree if tt.original == null => // same exception as in checkTypeRef
            case _: DefDef =>
            case _ => reporter.error(tree.pos, s"Only methods can be marked @varargs")
          }
        case _ =>
      }
      def applyChecks(annots: List[AnnotationInfo]): List[AnnotationInfo] = if (annots.isEmpty) Nil else {
        annots.foreach { ann =>
          checkVarArgs(ann.atp, tree)
          RefCheckTypeMap.check(ann.atp, tree)
          if (ann.original != null && ann.original.hasExistingSymbol)
            checkUndesiredProperties(ann.original.symbol, tree.pos)
        }
        val annotsBySymbol = new mutable.LinkedHashMap[Symbol, ListBuffer[AnnotationInfo]]()
        val transformedAnnots = {
          val saved = inAnnotation
          inAnnotation = true
          try annots.map(_.transformArgs(transformTrees)) finally inAnnotation = saved
        }
        for (transformedAnnot <- transformedAnnots) {
          val buffer = annotsBySymbol.getOrElseUpdate(transformedAnnot.symbol, new ListBuffer)
          buffer += transformedAnnot
        }
        annotsBySymbol.iterator.flatMap(x => groupRepeatableAnnotations(x._1, x._2.toList)).toList
      }

      // assumes non-empty `anns`
      def groupRepeatableAnnotations(sym: Symbol, anns: List[AnnotationInfo]): List[AnnotationInfo] =
        if (!sym.isJavaDefined) anns
        else anns match {
          case single :: Nil => anns
          case multiple      =>
            sym.getAnnotation(AnnotationRepeatableAttr) match {
              case Some(repeatable) =>
                repeatable.assocs.collectFirst {
                  case (nme.value, LiteralAnnotArg(Constant(c: Type))) => c
                } match {
                  case Some(container) =>
                    val assocs = List(
                      nme.value -> ArrayAnnotArg(multiple.map(NestedAnnotArg(_)).toArray)
                    )
                    AnnotationInfo(container, args = Nil, assocs = assocs) :: Nil
                  case None =>
                    devWarning(s"@Repeatable $sym had no containing class")
                    multiple
                }
              case None =>
                reporter.error(tree.pos, s"$sym may not appear multiple times on ${tree.symbol}")
                multiple
            }
        }

      def checkIsElidable(sym: Symbol): Unit = if (sym ne null) sym.elisionLevel.foreach { level =>
        if (!sym.isMethod || sym.isAccessor || sym.isLazy || sym.isDeferred) {
          val rest = if (sym.isDeferred) " The annotation affects only the annotated method, not overriding methods in subclasses." else ""
          reporter.error(sym.pos, s"${sym.name}: Only concrete methods can be marked @elidable.$rest")
        }
      }
      checkIsElidable(tree.symbol)

      def checkMember(sym: Symbol): Unit = {
        sym.setAnnotations(applyChecks(sym.annotations))

        // validate implicitNotFoundMessage and implicitAmbiguousMessage
        if (settings.lintImplicitNotFound) {
          def messageWarning(name: String)(warn: String) =
            refchecksWarning(tree.pos, s"Invalid $name message for ${sym}${sym.locationString}:\n$warn", WarningCategory.LintImplicitNotFound)
          analyzer.ImplicitNotFoundMsg.check(sym) foreach messageWarning("implicitNotFound")
          analyzer.ImplicitAmbiguousMsg.check(sym) foreach messageWarning("implicitAmbiguous")
        }

        if (settings.warnSerialization && sym.isClass && sym.hasAnnotation(SerialVersionUIDAttr)) {
          def warn(what: String) =
            refchecksWarning(tree.pos, s"@SerialVersionUID has no effect on $what", WarningCategory.LintSerial)

          if (sym.isTrait) warn("traits")
          else if (!sym.isSerializable) warn("non-serializable classes")
        }
        if (!sym.isMethod && !sym.isConstructor)
          checkNoThrows(sym.annotations)
      }
      def checkNoThrows(anns: List[AnnotationInfo]): Unit =
        if (anns.exists(_.symbol == ThrowsClass))
          reporter.error(tree.pos, s"`@throws` only allowed for methods and constructors")

      tree match {
        case m: MemberDef =>
          checkMember(m.symbol)
        case tpt@TypeTree() =>
          if (tpt.original != null)
            tpt.original.foreach {
              case dc: TypeTreeWithDeferredRefCheck =>
                applyRefchecksToAnnotations(dc.check()) // #2416
              case _ =>
            }
          if (!inPattern)
            tree.setType(tree.tpe.map {
              case AnnotatedType(anns, ul) =>
                checkNoThrows(anns)
                AnnotatedType(applyChecks(anns), ul)
              case tp => tp
            })
        case _ =>
      }
    }

    private def isSimpleCaseApply(tree: Tree): Boolean = {
      val sym = tree.symbol
      def isClassTypeAccessible(tree: Tree): Boolean = tree match {
        case TypeApply(fun, targs) =>
          isClassTypeAccessible(fun)
        case Select(module, apply) =>
          // scala/bug#4859 `CaseClass1().InnerCaseClass2()` must not be rewritten to `new InnerCaseClass2()`;
          //          {expr; Outer}.Inner() must not be rewritten to `new Outer.Inner()`.
          treeInfo.isQualifierSafeToElide(module) &&
          // scala/bug#5626 Classes in refinement types cannot be constructed with `new`.
          !module.exists { case t @ Select(_, _) => t.symbol != null && t.symbol.isStructuralRefinementMember case _ => false }
        case x => throw new MatchError(x)
      }
      sym.name == nme.apply &&
        !sym.hasStableFlag && // ???
        sym.isCase &&
        isClassTypeAccessible(tree) &&
        !tree.tpe.finalResultType.typeSymbol.primaryConstructor.isLessAccessibleThan(tree.symbol)
    }

    private def transformCaseApply(tree: Tree) = {
      def loop(t: Tree): Unit = t match {
        case Ident(_) =>
          checkUndesiredProperties(t.symbol, t.pos)
        case Select(qual, _) =>
          checkUndesiredProperties(t.symbol, t.pos)
          loop(qual)
        case _ =>
      }

      tree foreach {
        case i@Ident(_) =>
          enterReference(i.pos, i.symbol) // scala/bug#5390 need to `enterReference` for `a` in `a.B()`
        case _ =>
      }
      loop(tree)
      toConstructor(tree.pos, tree.tpe)
    }

    private def transformApply(tree: Apply): Tree = tree match {
      case Apply(
        Select(qual, nme.withFilter),
        List(Function(
          List(ValDef(_, pname, tpt, _)),
          Match(_, CaseDef(pat1, _, _) :: _))))
        if ((pname startsWith nme.CHECK_IF_REFUTABLE_STRING) &&
            isIrrefutable(pat1, tpt.tpe) && (qual.tpe <:< tree.tpe)) =>

          transform(qual)
      case Apply(fn, args) =>
        // sensicality should be subsumed by the unreachability/exhaustivity/irrefutability
        // analyses in the pattern matcher
        if (!inPattern) {
          checkImplicitViewOptionApply(tree.pos, fn, args)
          checkSensible(tree.pos, fn, args) // TODO: this should move to preEraseApply, as reasoning about runtime semantics makes more sense in the JVM type system
          checkNamedBooleanArgs(fn, args)
        }
        currentApplication = tree
        tree
    }

    /** Check that boolean literals are passed as named args.
     *  The rule is enforced when the type of the parameter is `Boolean`.
     *  The rule is relaxed when the method has exactly one boolean parameter
     *  and it is the first parameter, such as `assert(false, msg)`.
     */
    private def checkNamedBooleanArgs(fn: Tree, args: List[Tree]): Unit = {
      val sym = fn.symbol
      def applyDepth: Int = {
        def loop(t: Tree, d: Int): Int =
          t match {
            case Apply(f, _) => loop(f, d+1)
            case _ => d
          }
        loop(fn, 0)
      }
      def isAssertParadigm(params: List[Symbol]): Boolean = !sym.isConstructor && !sym.isCaseApplyOrUnapply && {
        params match {
          case h :: t => h.tpe == BooleanTpe && !t.exists(_.tpe == BooleanTpe)
          case _ => false
        }
      }
      if (settings.lintNamedBooleans && !sym.isJavaDefined && !args.isEmpty) {
        val params = sym.paramLists(applyDepth)
        if (!isAssertParadigm(params))
          foreach2(args, params)((arg, param) => arg match {
            case Literal(Constant(_: Boolean))
            if arg.hasAttachment[UnnamedArg.type] && param.tpe.typeSymbol == BooleanClass && !param.deprecatedParamName.contains(nme.NO_NAME) =>
              runReporting.warning(arg.pos, s"Boolean literals should be passed using named argument syntax for parameter ${param.name}.", WarningCategory.LintNamedBooleans, sym)
            case _ =>
          })
      }
    }

    private def transformSelect(tree: Select): Tree = {
      val Select(qual, name) = tree
      val sym = tree.symbol

      checkUndesiredProperties(sym, tree.pos)
      checkDelayedInitSelect(qual, sym, tree.pos)

      if (!sym.exists)
        devWarning("Select node has NoSymbol! " + tree + " / " + tree.tpe)

      if (name == nme.synchronized_ && isBoxedValueClass(qual.tpe.typeSymbol))
        refchecksWarning(tree.pos, s"Suspicious `synchronized` call involving boxed primitive `${qual.tpe.typeSymbol.name}`", WarningCategory.LintUniversalMethods)

      def checkSuper(mix: Name) =
        // term should have been eliminated by super accessors
        assert(!(qual.symbol.isTrait && sym.isTerm && mix == tpnme.EMPTY), (qual.symbol, sym, mix))

      // Rewrite eligible calls to monomorphic case companion apply methods to the equivalent constructor call.
      //
      // Note: for generic case classes the rewrite needs to be handled at the enclosing `TypeApply` to transform
      // `TypeApply(Select(C, apply), targs)` to `Select(New(C[targs]), <init>)`. In case such a `TypeApply`
      // was deemed ineligible for transformation (e.g. the case constructor was private), the refchecks transform
      // will recurse to this point with `Select(C, apply)`, which will have a type `[T](...)C[T]`.
      //
      // We don't need to perform the check on the Select node, and `!isHigherKinded will guard against this
      // redundant (and previously buggy, scala/bug#9546) consideration.
      if (!tree.tpe.isHigherKinded && isSimpleCaseApply(tree)) {
        transformCaseApply(tree)
      } else {
        qual match {
          case Super(_, mix)  => checkSuper(mix)
          case _              =>
        }
        tree
      }
    }
    private def transformIf(tree: If): Tree = {
      val If(cond, thenpart, elsepart) = tree
      def unitIfEmpty(t: Tree): Tree =
        if (t == EmptyTree) Literal(Constant(())).setPos(tree.pos).setType(UnitTpe) else t

      cond.tpe match {
        case FoldableConstantType(value) =>
          val res = if (value.booleanValue) thenpart else elsepart
          unitIfEmpty(res)
        case _ => tree
      }
    }

    // Warning about nullary methods returning Unit.
    private def checkNullaryMethodReturnType(sym: Symbol) = sym.tpe match {
      case NullaryMethodType(restpe) if restpe.typeSymbol == UnitClass =>
        // this may be the implementation of e.g. a generic method being parameterized
        // on Unit, in which case we had better let it slide.
        val isOk = (
             sym.isGetter
          || sym.isDefaultGetter
          || sym.allOverriddenSymbols.exists(over => !(over.tpe.resultType =:= sym.tpe.resultType))
          || sym.isArtifact
        )
        if (!isOk) {
          val msg = s"side-effecting nullary methods are discouraged: suggest defining as `def ${sym.name.decode}()` instead"
          val namePos = sym.pos.focus.withEnd(sym.pos.point + sym.decodedName.length)
          val action =
            if (namePos.source.sourceAt(namePos) == sym.decodedName)
              runReporting.codeAction("add empty parameter list", namePos.focusEnd, "()", msg)
            else Nil
          refchecksWarning(sym.pos, msg, WarningCategory.LintNullaryUnit, action)
        }
      case _ => ()
    }

    // Verify classes extending AnyVal meet the requirements
    private def checkAnyValSubclass(clazz: Symbol) =
      if (clazz.isDerivedValueClass) {
        if (clazz.isTrait)
          reporter.error(clazz.pos, "Only classes (not traits) are allowed to extend AnyVal")
        else if (clazz.hasAbstractFlag)
          reporter.error(clazz.pos, "`abstract` modifier cannot be used with value classes")
      }

    private def checkUnexpandedMacro(t: Tree) =
      if (!t.isDef && t.hasSymbolField && t.symbol.isTermMacro)
        reporter.error(t.pos, "macro has not been expanded")

    // if expression in statement position (of template or block)
    // looks like a useful value that should not be ignored, warn and return true
    // User specifies that an expression is boring by ascribing `e: Unit`.
    // The subtree `e` will bear an attachment, but may be wrapped in adaptations.
    private def checkInterestingResultInStatement(t: Tree): Boolean = {
      def isUninterestingSymbol(sym: Symbol): Boolean =
        sym != null && (
          sym.isConstructor ||
          sym.hasPackageFlag ||
          sym.isPackageObjectOrClass ||
          sym == BoxedUnitClass ||
          sym == AnyClass ||
          sym == AnyRefClass ||
          sym == AnyValClass
        )
      def isUninterestingType(tpe: Type): Boolean =
        tpe != null && (
          isUnitType(tpe) ||
          tpe.typeSymbol.isBottomClass ||
          tpe =:= UnitTpe ||
          tpe =:= BoxedUnitTpe ||
          isTrivialTopType(tpe)
        )
      // java lacks this.type idiom to distinguish side-effecting method, so ignore result of invoking java method.
      def isJavaApplication(t: Tree): Boolean = t match {
        case Apply(f, _) => f.symbol.isJavaDefined && !isUniversalMember(f.symbol)
        case _ => false
      }
      // The quirk of typechecking if is that the LUB often results in boring types.
      // Parser adds suppressing attachment on `if (b) expr` when user has `-Wnonunit-if:false`.
      def checkInterestingShapes(t: Tree): Boolean =
        t match {
          case If(_, thenpart, elsepart) => checkInterestingShapes(thenpart) || checkInterestingShapes(elsepart) // either or
          //case Block(_, Apply(label, Nil)) if label.symbol != null && nme.isLoopHeaderLabel(label.symbol.name) => false
          case Block(_, res) => checkInterestingShapes(res)
          case Match(_, cases) => cases.exists(k => checkInterestingShapes(k.body))
          case _ => checksForInterestingResult(t)
        }
      // tests for various flavors of blandness in expressions.
      def checksForInterestingResult(t: Tree): Boolean = (
           !t.isDef && !treeInfo.isPureDef(t)     // ignore defs
        && !isUninterestingSymbol(t.symbol)       // ctors, package, Unit, Any
        && !isUninterestingType(t.tpe)            // bottom types, Unit, Any
        && !treeInfo.isThisTypeResult(t)          // buf += x
        && !treeInfo.isSuperConstrCall(t)         // just a thing
        && !treeInfo.hasExplicitUnit(t)           // suppressed by explicit expr: Unit
        && !isJavaApplication(t)                  // Java methods are inherently side-effecting
      )
      // begin checkInterestingResultInStatement
      settings.warnNonUnitStatement.value && checkInterestingShapes(t) && {
        val where = t match {
          case Block(_, res) => res
          case If(_, thenpart, Literal(Constant(()))) =>
            thenpart match {
              case Block(_, res) => res
              case _ => thenpart
            }
          case _ => t
        }
        def msg = s"unused value of type ${where.tpe} (add `: Unit` to discard silently)"
        refchecksWarning(where.pos, msg, WarningCategory.OtherPureStatement)
        true
      }
    } // end checkInterestingResultInStatement

    override def transform(tree: Tree): Tree = {
      val savedLocalTyper = localTyper
      val savedCurrentApplication = currentApplication
      try {
        val sym = tree.symbol

        // Apply RefChecks to annotations. Makes sure the annotations conform to
        // type bounds (bug #935), issues deprecation warnings for symbols used
        // inside annotations.
        applyRefchecksToAnnotations(tree)
        val result: Tree = tree match {
          // NOTE: a val in a trait is now a DefDef, with the RHS being moved to an Assign in Constructors
          case tree: ValOrDefDef =>
            checkDeprecatedOvers(tree)
            if (!tree.isErroneous)
              checkInfiniteLoop(tree.symbol, tree.rhs)

            if (settings.warnNullaryUnit)
              checkNullaryMethodReturnType(sym)
            if (settings.warnInaccessible) {
              if (!sym.isConstructor && !sym.isEffectivelyFinalOrNotOverridden && !sym.owner.isSealed && !sym.isSynthetic)
                checkAccessibilityOfReferencedTypes(tree)
            }
            tree match {
              case dd: DefDef if sym.hasAnnotation(NativeAttr) =>
                if (sym.owner.isTrait) {
                  reporter.error(tree.pos, "A trait cannot define a native method.")
                  tree
                } else if (dd.rhs == EmptyTree) {
                  // pretend it had a stub implementation
                  sym resetFlag DEFERRED
                  deriveDefDef(dd)(_ => typed(gen.mkThrowNewRuntimeException("native method stub")))
                } else
                  tree
              case _ => tree
            }

          case Template(parents, self, body) =>
            localTyper = localTyper.atOwner(tree, currentOwner)
            for (stat <- body)
              if (!checkInterestingResultInStatement(stat) && treeInfo.isPureExprForWarningPurposes(stat)) {
                val msg = "a pure expression does nothing in statement position"
                val clause = if (body.lengthCompare(1) > 0) "; multiline expressions may require enclosing parentheses" else ""
                refchecksWarning(stat.pos, s"$msg$clause", WarningCategory.OtherPureStatement)
              }
            validateBaseTypes(currentOwner)
            checkOverloadedRestrictions(currentOwner, currentOwner)
            // scala/bug#7870 default getters for constructors live in the companion module
            checkOverloadedRestrictions(currentOwner, currentOwner.companionModule)
            val bridges = addVarargBridges(currentOwner) // TODO: do this during uncurry?
            checkAllOverrides(currentOwner)
            checkAnyValSubclass(currentOwner)
            if (currentOwner.isDerivedValueClass)
              currentOwner.primaryConstructor makeNotPrivate NoSymbol // scala/bug#6601, must be done *after* pickler!
            if (bridges.nonEmpty) deriveTemplate(tree)(_ ::: bridges) else tree

          case _: TypeTreeWithDeferredRefCheck => abort("adapt should have turned dc: TypeTreeWithDeferredRefCheck into tpt: TypeTree, with tpt.original == dc")
          case tpt@TypeTree() =>
            if(tpt.original != null) {
              tpt.original foreach {
                case dc: TypeTreeWithDeferredRefCheck =>
                  transform(dc.check()) // #2416 -- only call transform to do refchecks, but discard results
                  // tpt has the right type if the deferred checks are ok
                case _ =>
              }
            }

            tree.setType(RefCheckTypeMap.check(tree.tpe, tree, inPattern))

          case TypeApply(fn, args) =>
            checkBounds(tree, NoPrefix, NoSymbol, fn.tpe.typeParams, args map (_.tpe))
            if (isSimpleCaseApply(tree))
              transformCaseApply(tree)
            else
              tree

          case x @ Apply(_, _)  =>
            transformApply(x)

          case x @ If(_, _, _)  =>
            transformIf(x)

          case New(tpt) =>
            enterReference(tree.pos, tpt.tpe.typeSymbol)
            tree

          case treeInfo.WildcardStarArg(_) =>
            checkRepeatedParamArg(tree)
            tree

          case Ident(name) =>
            checkUndesiredProperties(sym, tree.pos)
            if (name != nme.WILDCARD && name != tpnme.WILDCARD_STAR) {
              assert(sym != NoSymbol, "transformCaseApply: name = " + name.debugString + " tree = " + tree + " / " + tree.getClass) //debug
              enterReference(tree.pos, sym)
            }
            tree

          case x @ Select(_, _) =>
            transformSelect(x)

          case Literal(Constant(tpe: Type)) =>
            RefCheckTypeMap.check(tpe, tree)
            tree

          case UnApply(fun, args) =>
            transform(fun) // just make sure we enterReference for unapply symbols, note that super.transform(tree) would not transform(fun)
                           // transformTrees(args) // TODO: is this necessary? could there be forward references in the args??
                           // probably not, until we allow parameterised extractors
            tree

          case blk @ Block(stats, expr) =>
            // diagnostic info
            val (count, result0, adapted) =
              expr match {
                case Block(expr :: Nil, Literal(Constant(()))) => (1, expr, true)
                case Literal(Constant(()))                     => (0, EmptyTree, false)
                case _                                         => (1, EmptyTree, false)
              }
            val isMultiline = stats.lengthCompare(1 - count) > 0

            def checkPure(t: Tree, supple: Boolean): Unit =
              if (!treeInfo.hasExplicitUnit(t) && treeInfo.isPureExprForWarningPurposes(t)) {
                val msg = "a pure expression does nothing in statement position"
                val parens = if (isMultiline) "multiline expressions might require enclosing parentheses" else ""
                val discard = if (adapted) "; a value can be silently discarded when Unit is expected" else ""
                val text =
                  if (supple) s"$parens$discard"
                  else if (!parens.isEmpty) s"$msg; $parens" else msg
                refchecksWarning(t.pos, text, WarningCategory.OtherPureStatement)
              }
            // check block for unintended "expression in statement position"
            stats.foreach { t => if (!checkInterestingResultInStatement(t)) checkPure(t, supple = false) }
            if (result0.nonEmpty) checkPure(result0, supple = true)

            def checkImplicitlyAdaptedBlockResult(t: Tree): Unit =
              expr match {
                case treeInfo.Applied(f, _, _) if f.symbol != null && f.symbol.isImplicit =>
                  f.symbol.paramLists match {
                    case (p :: Nil) :: _ if p.isByNameParam => refchecksWarning(t.pos, s"Block result was adapted via implicit conversion (${f.symbol}) taking a by-name parameter", WarningCategory.LintBynameImplicit)
                    case _ =>
                  }
                case _ =>
              }
            if (isMultiline && settings.warnByNameImplicit) checkImplicitlyAdaptedBlockResult(expr)

            tree
          case Match(selector, cases) =>
            // only warn if it could be put in backticks in a pattern
            def isWarnable(sym: Symbol): Boolean =
              sym != null && sym.exists &&
              !sym.hasPackageFlag && sym.isStable && !isByName(sym) &&
              !sym.hasAttachment[PatVarDefAttachment.type] // val (_, v) = with one var is shadowed in desugaring
              //!toCheck.isSynthetic // self-type symbols are synthetic: value self (<synthetic>), do warn

            class CheckSelector extends InternalTraverser {
              var selectorSymbols: List[Symbol] = null
              override def traverse(t: Tree): Unit = {
                val include = t match {
                  case _: This    => true // !t.symbol.isStable
                  case _: SymTree => isWarnable(t.symbol)
                  case _          => false
                }
                if (include) selectorSymbols ::= t.symbol
                t.traverse(this)
              }
              // true if the shadowed toCheck appears in the selector expression
              def implicatesSelector(toCheck: Symbol): Boolean = {
                if (selectorSymbols == null) {
                  selectorSymbols = Nil
                  apply(selector)
                }
                selectorSymbols.exists(sym => sym.eq(toCheck) || sym.accessedOrSelf.eq(toCheck.accessedOrSelf) ||
                  toCheck.isThisSym && toCheck.owner == sym) // self match { case self: S => }, selector C.this is class symbol
              }
            }
            val checkSelector = new CheckSelector
            // true to warn about shadowed when selSym is the scrutinee
            def checkShadowed(shadowed: Symbol): Boolean = {
              def checkShadowedSymbol(toCheck: Symbol): Boolean =
                isWarnable(toCheck) && !checkSelector.implicatesSelector(toCheck)

              if (shadowed.isOverloaded) shadowed.alternatives.exists(checkShadowedSymbol)
              else checkShadowedSymbol(shadowed)
            }
            // warn if any checkable pattern var shadows, in the context of the selector,
            // or for `tree match case Apply(fun, args) =>` check whether names in args equal names of fun.params
            def checkPattern(p: Tree): Unit = {
              val traverser = new InternalTraverser {
                // names absolved of shadowing because it is a "current" parameter (of a case class, etc)
                var absolved: List[Name] = Nil
                override def traverse(t: Tree): Unit = t match {
                  case Apply(_, args) =>
                    treeInfo.dissectApplied(t).core.tpe match {
                      case MethodType(ps, _) =>
                        foreach2(ps, args) { (p, arg) =>
                          absolved ::= p.name
                          try traverse(arg)
                          finally absolved = absolved.tail
                        }
                      case _ => t.traverse(this)
                    }
                  case bind @ Bind(name, _) =>
                    def richLocation(sym: Symbol): String = sym.ownsString match {
                      case ""   => val n = sym.pos.line; if (n > 0) s"$sym at line $n" else sym.fullLocationString
                      case owns => s"$sym in $owns"
                    }
                    for (shade <- bind.getAndRemoveAttachment[PatShadowAttachment]) {
                      val shadowed = shade.shadowed
                      if (!absolved.contains(name) && !bind.symbol.hasTransOwner(shadowed.accessedOrSelf) && checkShadowed(shadowed))
                        refchecksWarning(bind.pos, s"Name $name is already introduced in an enclosing scope as ${richLocation(shadowed)}. Did you intend to match it using backquoted `$name`?", WarningCategory.OtherShadowing)

                    }
                  case _ => t.traverse(this)
                }
              }
              traverser(p)
            }
            // check the patterns for unfriendly shadowing, patvars bearing PatShadowAttachment
            if (settings.warnPatternShadow) for (cdef <- cases) checkPattern(cdef.pat)
            tree
          case _ => tree
        }

        // skip refchecks in patterns....
        val result1 = result match {
          case CaseDef(pat, guard, body) =>
            val pat1 = savingInPattern {
              inPattern = true
              transform(pat)
            }
            treeCopy.CaseDef(tree, pat1, transform(guard), transform(body))
          case _ =>
            result.transform(this)
        }
        result1 match {
          case ClassDef(_, _, _, _) | TypeDef(_, _, _, _) | ModuleDef(_, _, _) =>
            if (result1.symbol.isLocalToBlock || result1.symbol.isTopLevel)
              varianceValidator.traverse(result1)
          case tt @ TypeTree() if tt.original != null =>
            varianceValidator.validateVarianceOfPolyTypesIn(tt.tpe)
          case _ =>
        }

        checkUnexpandedMacro(result1)

        result1
      } catch {
        case ex: TypeError =>
          if (settings.isDebug) ex.printStackTrace()
          reporter.error(tree.pos, ex.getMessage())
          tree
      } finally {
        localTyper = savedLocalTyper
        currentApplication = savedCurrentApplication
      }
    }
  }
}


================================================
FILE: examples/SyntaxAnalyzer.scala
================================================
/* NSC -- new Scala compiler
 * Copyright 2005-2013 LAMP/EPFL
 * @author Martin Odersky
 */

package scala.tools.nsc
package ast.parser

import javac._

/** An nsc sub-component.
 */
abstract class SyntaxAnalyzer extends SubComponent with Parsers with MarkupParsers with Scanners with JavaParsers with JavaScanners {
  import global._

  val phaseName = "parser"
  def newPhase(prev: Phase): StdPhase = new ParserPhase(prev)

  abstract class MemberDefTraverser extends Traverser {
    def onMember(defn: MemberDef): Unit

    private var depth: Int = 0
    private def lower[T](body: => T): T = {
      depth += 1
      try body finally depth -= 1
    }
    def currentDepth = depth

    /** Prune this tree and all trees beneath it. Can be overridden. */
    def prune(md: MemberDef): Boolean = (
         md.mods.isSynthetic
      || md.mods.isParamAccessor
      || nme.isConstructorName(md.name)
      || (md.name containsName nme.ANON_CLASS_NAME)
    )

    override def traverse(t: Tree): Unit = t match {
      case md: MemberDef if prune(md) =>
      case md @ PackageDef(_, stats)  => traverseTrees(stats)
      case md: ImplDef                => onMember(md) ; lower(traverseTrees(md.impl.body))
      case md: ValOrDefDef            => onMember(md) ; lower(traverse(md.rhs))
      case _                          => super.traverse(t)
    }
  }

  class MemberPosReporter(unit: CompilationUnit) extends MemberDefTraverser {
    private var outputFn: MemberDef => String = outputForScreen
    val path = unit.source.file.path

    // If a single line, outputs the line; if it spans multiple lines
    // outputs NN,NN with start and end lines, e.g. 15,25.
    def outputPos(md: MemberDef): String = {
      val pos   = md.pos
      val start = pos.focusStart.line
      val end   = pos.focusEnd.line

      if (start == end) "" + start else s"$start,$end"
    }
    def outputForSed(md: MemberDef): String = {
      val pos_s = "%-12s" format outputPos(md) + "p"
      s"$pos_s $path    # ${md.keyword} ${md.name}"
    }
    def outputForScreen(md: MemberDef): String = {
      val pos_s = "%-20s" format " " * currentDepth + outputPos(md)
      s"$pos_s ${md.keyword} ${md.name}"
    }

    def onMember(md: MemberDef) = println(outputFn(md))
    // It recognizes "sed" and "anything else".
    def show(style: String) {
      if (style == "sed") {
        outputFn = outputForSed
        traverse(unit.body)
      }
      else {
        outputFn = outputForScreen
        println(path)
        traverse(unit.body)
      }
      println("")
    }
  }

  private def initialUnitBody(unit: CompilationUnit): Tree = {
    if (unit.isJava) newJavaUnitParser(unit).parse()
    else if (currentRun.parsing.incompleteHandled) newUnitParser(unit).parse()
    else newUnitParser(unit).smartParse()
  }

  class ParserPhase(prev: Phase) extends StdPhase(prev) {
    override val checkable = false
    override val keepsTypeParams = false

    def apply(unit: CompilationUnit) {
      informProgress("parsing " + unit)
      // if the body is already filled in, don't overwrite it
      // otherwise compileLate is going to overwrite bodies of synthetic source files
      if (unit.body == EmptyTree)
        unit.body = initialUnitBody(unit)

      if (settings.Yrangepos && !reporter.hasErrors)
        validatePositions(unit.body)

      if (settings.Ymemberpos.isSetByUser)
        new MemberPosReporter(unit) show (style = settings.Ymemberpos.value)
    }
  }
}

================================================
FILE: examples/Variance.scala
================================================
class Function1[-T1, +R]


================================================
FILE: go.mod
================================================
module github.com/tree-sitter/tree-sitter-scala

go 1.22

require github.com/tree-sitter/go-tree-sitter v0.24.0

require github.com/mattn/go-pointer v0.0.1 // indirect


================================================
FILE: go.sum
================================================
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/mattn/go-pointer v0.0.1 h1:n+XhsuGeVO6MEAp7xyEukFINEa+Quek5psIR/ylA6o0=
github.com/mattn/go-pointer v0.0.1/go.mod h1:2zXcozF6qYGgmsG+SeTZz3oAbFLdD3OWqnUbNvJZAlc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tree-sitter/go-tree-sitter v0.24.0 h1:kRZb6aBNfcI/u0Qh8XEt3zjNVnmxTisDBN+kXK0xRYQ=
github.com/tree-sitter/go-tree-sitter v0.24.0/go.mod h1:x681iFVoLMEwOSIHA1chaLkXlroXEN7WY+VHGFaoDbk=
github.com/tree-sitter/tree-sitter-c v0.21.5-0.20240818205408-927da1f210eb h1:A8425heRM8mylnv4H58FPUiH+aYivyitre0PzxrfmWs=
github.com/tree-sitter/tree-sitter-c v0.21.5-0.20240818205408-927da1f210eb/go.mod h1:dOF6gtQiF9UwNh995T5OphYmtIypkjsp3ap7r9AN/iA=
github.com/tree-sitter/tree-sitter-cpp v0.22.4-0.20240818224355-b1a4e2b25148 h1:AfFPZwtwGN01BW1jDdqBVqscTwetvMpydqYZz57RSlc=
github.com/tree-sitter/tree-sitter-cpp v0.22.4-0.20240818224355-b1a4e2b25148/go.mod h1:Bh6U3viD57rFXRYIQ+kmiYtr+1Bx0AceypDLJJSyi9s=
github.com/tree-sitter/tree-sitter-embedded-template v0.21.1-0.20240819044651-ffbf64942c33 h1:TwqSV3qLp3tKSqirGLRHnjFk9Tc2oy57LIl+FQ4GjI4=
github.com/tree-sitter/tree-sitter-embedded-template v0.21.1-0.20240819044651-ffbf64942c33/go.mod h1:CvCKCt3v04Ufos1zZnNCelBDeCGRpPucaN8QczoUsN4=
github.com/tree-sitter/tree-sitter-go v0.21.3-0.20240818010209-8c0f0e7a6012 h1:Xvxck3tE5FW7F7bTS97iNM2ADMyCMJztVqn5HYKdJGo=
github.com/tree-sitter/tree-sitter-go v0.21.3-0.20240818010209-8c0f0e7a6012/go.mod h1:T40D0O1cPvUU/+AmiXVXy1cncYQT6wem4Z0g4SfAYvY=
github.com/tree-sitter/tree-sitter-html v0.20.5-0.20240818004741-d11201a263d0 h1:c46K6uh5Dz00zJeU9BfjXdb8I+E4RkUdfnWJpQADXFo=
github.com/tree-sitter/tree-sitter-html v0.20.5-0.20240818004741-d11201a263d0/go.mod h1:hcNt/kOJHcIcuMvouE7LJcYdeFUFbVpBJ6d4wmOA+tU=
github.com/tree-sitter/tree-sitter-java v0.21.1-0.20240824015150-576d8097e495 h1:jrt4qbJVEFs4H93/ITxygHc6u0TGqAkkate7TQ4wFSA=
github.com/tree-sitter/tree-sitter-java v0.21.1-0.20240824015150-576d8097e495/go.mod h1:oyaR7fLnRV0hT9z6qwE9GkaeTom/hTDwK3H2idcOJFc=
github.com/tree-sitter/tree-sitter-javascript v0.21.5-0.20240818005344-15887341e5b5 h1:om4X9AVg3asL8gxNJDcz4e/Wp+VpQj1PY3uJXKr6EOg=
github.com/tree-sitter/tree-sitter-javascript v0.21.5-0.20240818005344-15887341e5b5/go.mod h1:nNqgPoV/h9uYWk6kYEFdEAhNVOacpfpRW5SFmdaP4tU=
github.com/tree-sitter/tree-sitter-json v0.21.1-0.20240818005659-bdd69eb8c8a5 h1:pfV3G3k7NCKqKk8THBmyuh2zA33lgYHS3GVrzRR8ry4=
github.com/tree-sitter/tree-sitter-json v0.21.1-0.20240818005659-bdd69eb8c8a5/go.mod h1:GbMKRjLfk0H+PI7nLi1Sx5lHf5wCpLz9al8tQYSxpEk=
github.com/tree-sitter/tree-sitter-php v0.22.9-0.20240819002312-a552625b56c1 h1:ZXZMDwE+IhUtGug4Brv6NjJWUU3rfkZBKpemf6RY8/g=
github.com/tree-sitter/tree-sitter-php v0.22.9-0.20240819002312-a552625b56c1/go.mod h1:UKCLuYnJ312Mei+3cyTmGOHzn0YAnaPRECgJmHtzrqs=
github.com/tree-sitter/tree-sitter-python v0.21.1-0.20240818005537-55a9b8a4fbfb h1:EXEM82lFM7JjJb6qiKZXkpIDaCcbV2obNn82ghwj9lw=
github.com/tree-sitter/tree-sitter-python v0.21.1-0.20240818005537-55a9b8a4fbfb/go.mod h1:lXCF1nGG5Dr4J3BTS0ObN4xJCCICiSu/b+Xe/VqMV7g=
github.com/tree-sitter/tree-sitter-ruby v0.21.1-0.20240818211811-7dbc1e2d0e2d h1:fcYCvoXdcP1uRQYXqJHRy6Hec+uKScQdKVtMwK9JeCI=
github.com/tree-sitter/tree-sitter-ruby v0.21.1-0.20240818211811-7dbc1e2d0e2d/go.mod h1:T1nShQ4v5AJtozZ8YyAS4uzUtDAJj/iv4YfwXSbUHzg=
github.com/tree-sitter/tree-sitter-rust v0.21.3-0.20240818005432-2b43eafe6447 h1:o9alBu1J/WjrcTKEthYtXmdkDc5OVXD+PqlvnEZ0Lzc=
github.com/tree-sitter/tree-sitter-rust v0.21.3-0.20240818005432-2b43eafe6447/go.mod h1:1Oh95COkkTn6Ezp0vcMbvfhRP5gLeqqljR0BYnBzWvc=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=


================================================
FILE: grammar.js
================================================
const PREC = {
  comment: 1,
  using_directive: 2,
  control: 1,
  stable_type_id: 2,
  type: 2,
  while: 2,
  assign: 3,
  case: 3,
  stable_id: 4,
  unit: 4,
  postfix: 5,
  colon_call: 5,
  infix: 6,
  prefix: 7,
  compound: 7,
  call: 8,
  field: 8,
  macro: 10,
  binding: 10,
};

module.exports = grammar({
  name: "scala",

  extras: $ => [/\s/, $.comment, $.block_comment],

  supertypes: $ => [$.expression, $._definition, $._pattern],

  externals: $ => [
    $._automatic_semicolon,
    $._indent,
    $._outdent,
    $._comma_outdent,
    $._simple_string_start,
    $._simple_string_middle,
    $._simple_multiline_string_start,
    $._interpolated_string_middle,
    $._interpolated_multiline_string_middle,
    $._raw_string_start,
    $._raw_string_middle,
    $._raw_string_multiline_middle,
    $._single_line_string_end,
    $._multiline_string_end,
    "else",
    "catch",
    "finally",
    "extends",
    "derives",
    "with",
    $.error_sentinel,
  ],

  inline: $ => [
    $._pattern,
    $._semicolon,
    $._definition,
    $._param_type,
    $._identifier,
    $._postfix_expression_choice,
    $._infix_type_choice,
    $._param_value_type,
    $._simple_type,
    $.literal,
  ],

  // Doc: https://tree-sitter.github.io/tree-sitter/creating-parsers, search "precedences"
  // These names can be used in the prec functions to define precedence relative only to other names in the array, rather than globally.
  precedences: $ => [
    ["mod", "soft_id"],
    ["end", "soft_id"],
    ["new", "structural_type"],
    ["self_type", "lambda"],
    ["annotation", "applied_constructor_type"],
    ["constructor_application", "applied_constructor_type"],
  ],

  conflicts: $ => [
    [$.tuple_type, $.parameter_types],
    [$.binding, $._simple_expression],
    [$.binding, $._type_identifier],
    [$.while_expression, $._simple_expression],
    [$.if_expression],
    [$.match_expression],
    [$._given_constructor, $._type_identifier],
    [$.instance_expression],
    // In case of: 'extension'  _indent  '{'  'case'  operator_identifier  'if'  operator_identifier  •  '=>'  …
    // we treat `operator_identifier` as `simple_expression`
    [$._simple_expression, $.lambda_expression],
    // operator_identifier  •  ':'  …
    [$._simple_expression, $._single_lambda_param],
    // 'class'  _class_constructor  •  _automatic_semicolon  …
    [$._class_definition],
    // 'class'  operator_identifier  •  _automatic_semicolon  …
    [$._class_constructor],
    // 'enum'  _class_constructor  '{'  'case'  operator_identifier  _full_enum_def_repeat1  •  _automatic_semicolon  …
    [$._full_enum_def],
    // _start_val  identifier  ','  identifier  •  ':'  …
    [$.identifiers, $.val_declaration],
    // 'enum'  operator_identifier  _automatic_semicolon  '('  ')'  •  ':'  …
    [$.class_parameters],
    // 'for'  operator_identifier  ':'  _annotated_type  •  ':'  …
    [$._type, $.compound_type],
    // 'for'  'given'  _annotated_type  •  '*'  …
    [$._type, $.infix_type],
    // _simple_expression  ':'  _annotated_type  •  'match'  …
    [$._type, $.match_type],
    // 'given'  '('  '['  _type_parameter  •  ','  …
    [$._variant_type_parameter, $.type_lambda],
    // 'given'  '('  operator_identifier  ':'  _type  •  ','  …
    [$.name_and_type, $.parameter],
    [$._simple_expression, $.binding, $.tuple_pattern],
    [$._simple_expression, $.tuple_pattern],
    [$._simple_expression, $._type_identifier],
    // 'if'  parenthesized_expression  •  '{'  …
    [$._if_condition, $._simple_expression],
    [$.block, $._braced_template_body1],
    [$._simple_expression, $._type_identifier],
    // '['  operator_identifier  ':'  '{'  operator_identifier  •  '=>'  …
    [$._single_lambda_param, $.self_type, $._type_identifier],
    // '['  operator_identifier  ':'  '{'  operator_identifier  •  '?=>'  …
    [$._single_lambda_param, $._type_identifier],
    // '('  operator_identifier  •  ':'  …
    [$._simple_expression, $._single_lambda_param, $.binding],
    // 'given'  '{'  operator_identifier  •  ':'  …
    [$._simple_expression, $._single_lambda_param, $.self_type],
    // '['  operator_identifier  ':'  '{'  operator_identifier  •  ':'  …
    [
      $._simple_expression,
      $._single_lambda_param,
      $.self_type,
      $._type_identifier,
    ],
    // 'given'  '{'  operator_identifier  ':'  _type  •  '=>'  …
    [$._single_lambda_param, $._self_type_ascription],
    [$.binding, $._simple_expression, $._type_identifier],
    [$.class_parameter, $._type_identifier],
    // '{'  _single_lambda_param  '=>'  expression  •  '}'  …
    [$._block, $._indentable_expression],
    [$.match_expression, $._simple_expression],
    // _  :  Type  •  '=>'  …
    [$.self_type, $._simple_expression],
    // 'for'  null_literal  _asterisk  •  '*'  …
    [$.repeat_pattern, $.operator_identifier],
    // _simple_expression  '('  _simple_expression  _asterisk  •  ')'  …
    [$.vararg, $.operator_identifier],
    // _simple_expression  '('  expression  •  ','  …
    [$._exprs_in_parens],
    // _simple_expression  ':'  '('  wildcard  •  ','  …
    [$._annotated_type, $.binding],
    // '['  identifier  ':'  '{'  wildcard  •  ':'  …
    [$.self_type, $._annotated_type, $._simple_expression],
    // '['  identifier  ':'  '{'  '('  wildcard  •  ':'  …
    [$.binding, $._annotated_type, $._simple_expression],
    // '['  identifier  ':'  '{'  wildcard  •  '{'  …
    [$._annotated_type, $._simple_expression],
    // '['  identifier  ':'  '{'  wildcard  •  '['  …
    [$.generic_type, $._simple_expression],
  ],

  word: $ => $._alpha_identifier,

  rules: {
    // TopStats          ::=  TopStat {semi TopStat}
    compilation_unit: $ =>
      seq(
        optional($._shebang),
        optional(trailingSep1($._semicolon, $._top_level_definition)),
      ),

    _top_level_definition: $ =>
      choice($._definition, $._end_marker, $.expression),

    _definition: $ =>
      choice(
        $.given_definition,
        $.extension_definition,
        $.class_definition,
        $.import_declaration,
        $.export_declaration,
        $.object_definition,
        $.enum_definition,
        $.trait_definition,
        $.val_definition,
        $.val_declaration,
        $.var_definition,
        $.var_declaration,
        $.type_definition,
        $.function_definition,
        $.function_declaration,
        $.package_clause,
        $.package_object,
      ),

    enum_definition: $ =>
      seq(
        repeat($.annotation),
        optional($.modifiers),
        "enum",
        $._class_constructor,
        field("extend", optional($.extends_clause)),
        field("derive", optional($.derives_clause)),
        field("body", $.enum_body),
      ),

    _enum_block: $ =>
      prec.left(
        seq(
          sep1(
            $._semicolon,
            choice($.enum_case_definitions, $.expression, $._definition),
          ),
          optional($._semicolon),
        ),
      ),

    enum_body: $ =>
      choice(
        prec.left(PREC.control, seq(":", $._indent, $._enum_block, $._outdent)),
        seq(
          "{",
          // TODO: self type
          optional($._enum_block),
          "}",
        ),
      ),

    enum_case_definitions: $ =>
      seq(
        repeat($.annotation),
        "case",
        choice(commaSep1($.simple_enum_case), $.full_enum_case),
      ),

    simple_enum_case: $ =>
      prec.left(
        seq(
          field("name", $._identifier),
          field("extend", optional($.extends_clause)),
        ),
      ),

    full_enum_case: $ => seq(field("name", $._identifier), $._full_enum_def),

    _full_enum_def: $ =>
      seq(
        field("type_parameters", optional($.type_parameters)),
        field("class_parameters", repeat1($.class_parameters)),
        field("extend", optional($.extends_clause)),
      ),

    package_clause: $ =>
      prec.right(
        seq(
          "package",
          field("name", $.package_identifier),
          // This is slightly more permissive than the EBNF in that it allows any
          // kind of declaration inside of the package blocks. As we're more
          // concerned with the structure rather than the validity of the program
          // we'll allow it.
          field("body", optional($.template_body)),
        ),
      ),

    package_identifier: $ => prec.right(sep1(".", $._identifier)),

    package_object: $ => seq("package", "object", $._object_definition),

    import_declaration: $ =>
      prec.left(seq("import", sep1(",", $._namespace_expression))),

    export_declaration: $ =>
      prec.left(seq("export", sep1(",", $._namespace_expression))),

    /*
      ImportExpr        ::=  SimpleRef {‘.’ id} ‘.’ ImportSpec
                          |  SimpleRef ‘as’ id
      ImportSpec        ::=  NamedSelector
                          |  WildCardSelector
                          | ‘{’ ImportSelectors) ‘}’
      NamedSelector     ::=  id [‘as’ (id | ‘_’)]
      WildCardSelector  ::=  ‘*’ | ‘given’ [InfixType]
    */
    _namespace_expression: $ =>
      prec.left(
        choice(
          seq(
            field("path", sep1(".", $._identifier)),
            optional(
              seq(
                ".",
                choice(
                  $.namespace_wildcard,
                  $.namespace_selectors,
                  // Only allowed in Scala 3
                  // ImportExpr        ::=
                  //    SimpleRef {‘.’ id} ‘.’ ImportSpec |  SimpleRef ‘as’ id
                  $.as_renamed_identifier,
                ),
              ),
            ),
          ),
          $.as_renamed_identifier,
        ),
      ),

    namespace_wildcard: $ => prec.left(1, choice("*", "_", "given")),

    _namespace_given_by_type: $ => seq("given", $._type),

    namespace_selectors: $ =>
      seq(
        "{",
        trailingCommaSep1(
          choice(
            $._namespace_given_by_type,
            $.namespace_wildcard,
            $._identifier,
            $.arrow_renamed_identifier,
            $.as_renamed_identifier,
          ),
        ),
        "}",
      ),

    // deprecated: Remove when highlight query is updated for Neovim
    _import_selectors: $ => alias($.namespace_selectors, $.import_selectors),

    arrow_renamed_identifier: $ =>
      seq(
        field("name", $._identifier),
        "=>",
        field("alias", choice($._identifier, $.wildcard)),
      ),

    as_renamed_identifier: $ =>
      seq(
        field("name", $._identifier),
        "as",
        field("alias", choice($._identifier, $.wildcard)),
      ),

    object_definition: $ =>
      seq(
        repeat($.annotation),
        optional($.modifiers),
        optional("case"),
        "object",
        $._object_definition,
      ),

    _object_definition: $ =>
      prec.left(
        seq(
          field("name", $._identifier),
          field("extend", optional($.extends_clause)),
          field("derive", optional($.derives_clause)),
          field("body", optional($._definition_body)),
        ),
      ),

    class_definition: $ =>
      seq(
        repeat($.annotation),
        optional($.modifiers),
        optional("case"),
        "class",
        $._class_definition,
      ),

    _class_definition: $ =>
      seq(
        $._class_constructor,
        field("extend", optional($.extends_clause)),
        field("derive", optional($.derives_clause)),
        field("body", optional($._definition_body)),
      ),

    _definition_body: $ =>
      seq(optional($._automatic_semicolon), field("body", $.template_body)),

    /**
     * ClassConstr       ::=  [ClsTypeParamClause] [ConstrMods] ClsParamClauses
     * ConstrMods        ::=  {Annotation} [AccessModifier]
     */
    _class_constructor: $ =>
      seq(
        field("name", $._identifier),
        field("type_parameters", optional($.type_parameters)),
        optional(alias($._constructor_annotation, $.annotation)),
        optional($.access_modifier),
        field(
          "class_parameters",
          repeat(seq(optional($._automatic_semicolon), $.class_parameters)),
        ),
      ),

    trait_definition: $ =>
      prec.left(
        seq(
          repeat($.annotation),
          optional($.modifiers),
          "trait",
          $._class_definition,
        ),
      ),

    // The EBNF makes a distinction between function type parameters and other
    // type parameters as you can't specify variance on function type
    // parameters. This isn't important to the structure of the AST so we don't
    // make that distinction.
    type_parameters: $ =>
      seq("[", trailingCommaSep1($._variant_type_parameter), "]"),

    _variant_type_parameter: $ =>
      seq(
        repeat($.annotation),
        choice(
          $.covariant_type_parameter,
          $.contravariant_type_parameter,
          $._type_parameter, // invariant type parameter
          $.type_lambda,
        ),
      ),

    covariant_type_parameter: $ => seq("+", $._type_parameter),

    contravariant_type_parameter: $ => seq("-", $._type_parameter),

    _type_parameter: $ =>
      seq(
        field("name", choice($.wildcard, $._identifier)),
        field("type_parameters", optional($.type_parameters)),
        field("bound", optional($.lower_bound)),
        field("bound", optional($.upper_bound)),
        field("bound", optional(repeat($.view_bound))),
        field("bound", optional($._context_bounds)),
      ),

    upper_bound: $ => seq("<:", field("type", $._type)),

    lower_bound: $ => seq(">:", field("type", $._type)),

    view_bound: $ => seq("<%", field("type", $._type)),

    _context_bounds: $ =>
      choice(
        repeat1(seq(":", $.context_bound)),
        seq(":", "{", trailingCommaSep1($.context_bound), "}"),
      ),

    context_bound: $ =>
      seq(
        field("type", $._type),
        optional(seq("as", field("name", $._identifier))),
      ),

    /*
     * TemplateBody      ::=  :<<< [SelfType] TemplateStat {semi TemplateStat} >>>
     */
    template_body: $ =>
      choice($._indented_template_body, $._braced_template_body),

    _indented_template_body: $ =>
      prec.left(
        PREC.control,
        seq(":", $._indent, optional($.self_type), $._block, $._outdent),
      ),

    _braced_template_body: $ =>
      prec.left(
        PREC.control,
        seq(
          "{",
          optional(choice($._braced_template_body1, $._braced_template_body2)),
          "}",
        ),
      ),

    _braced_template_body1: $ => seq(optional($.self_type), $._block),
    _braced_template_body2: $ =>
      seq(
        choice(
          seq($._indent, optional($.self_type)),
          seq(optional($.self_type), $._indent),
        ),
        optional($._block),
        $._outdent,
      ),

    /*
     * WithTemplateBody  ::=  <<< [SelfType] TemplateStat {semi TemplateStat} >>>
     */
    with_template_body: $ =>
      choice(
        prec.left(
          PREC.control,
          seq($._indent, optional($.self_type), $._block, $._outdent),
        ),
        seq("{", optional($._block), "}"),
      ),

    _extension_template_body: $ =>
      choice(
        prec.left(PREC.control, seq($._indent, $._block, $._outdent)),
        seq("{", optional($._block), "}"),
      ),

    _end_marker: $ =>
      prec.left(
        "end",
        seq(
          "end",
          choice(
            "if",
            "while",
            "for",
            "match",
            "try",
            "new",
            "this",
            "given",
            "extension",
            "val",
            alias($._identifier, "_end_ident"),
          ),
        ),
      ),

    // Dynamic precedences added here to win over $.call_expression
    self_type: $ =>
      prec.dynamic(
        1,
        prec(
          "self_type",
          seq(
            choice($._identifier, $.wildcard),
            optional($._self_type_ascription),
            "=>",
          ),
        ),
      ),

    _self_type_ascription: $ => seq(":", $._type),

    annotation: $ =>
      prec.right(
        "annotation",
        seq(
          "@",
          field("name", $._simple_type),
          field("arguments", repeat(prec("annotation", $.arguments))),
        ),
      ),

    // Only allows 0 or 1 argument lists as these annotations
    // usually come from Java, where multiple argument lists are not allowed
    _constructor_annotation: $ =>
      prec(
        "annotation",
        seq(
          "@",
          field("name", $._simple_type),
          optional(
            alias(
              seq(
                // token.immediate here carries an assumption that there are no spaces between
                // an annotation name and its argument list, otherwise this list should be
                // classified as a class constructor list
                token.immediate("("),
                optional($._exprs_in_parens),
                ")",
              ),
              $.arguments,
            ),
          ),
        ),
      ),

    val_definition: $ =>
      seq(
        $._start_val,
        field("pattern", choice($._pattern, $.identifiers)),
        optional(seq(":", field("type", $._type))),
        "=",
        field("value", $._indentable_expression),
      ),

    val_declaration: $ =>
      seq(
        $._start_val,
        commaSep1(field("name", $._identifier)),
        ":",
        field("type", $._type),
      ),

    _start_val: $ => seq(repeat($.annotation), optional($.modifiers), "val"),

    var_declaration: $ =>
      seq(
        $._start_var,
        commaSep1(field("name", $._identifier)),
        ":",
        field("type", $._type),
      ),

    var_definition: $ =>
      seq(
        $._start_var,
        field("pattern", choice($._pattern, $.identifiers)),
        optional(seq(":", field("type", $._type))),
        "=",
        field("value", $._indentable_expression),
      ),

    _start_var: $ => seq(repeat($.annotation), optional($.modifiers), "var"),

    type_definition: $ =>
      prec.left(
        seq(
          repeat($.annotation),
          optional($.modifiers),
          optional($.opaque_modifier),
          "type",
          $._type_constructor,
          optional(seq("=", field("type", $._type))),
        ),
      ),

    // Created for memory-usage optimization during codegen.
    _type_constructor: $ =>
      prec.left(
        seq(
          field("name", $._type_identifier),
          field("type_parameters", optional($.type_parameters)),
          field("bound", optional($.lower_bound)),
          field("bound", optional($.upper_bound)),
          field("bound", optional($._context_bounds)),
        ),
      ),

    function_definition: $ =>
      seq(
        $._function_declaration,
        choice(
          seq("=", field("body", $._indentable_expression)),
          field("body", $.block),
        ),
      ),

    function_declaration: $ => $._function_declaration,

    _function_declaration: $ =>
      prec.left(
        seq(
          repeat($.annotation),
          optional($.modifiers),
          "def",
          $._function_constructor,
          optional(seq(":", field("return_type", $._type))),
        ),
      ),

    // Created for memory-usage optimization during codegen.
    _function_constructor: $ =>
      prec.right(
        seq(
          field("name", $._identifier),
          field(
            "parameters",
            repeat(
              seq(
                optional($._automatic_semicolon),
                choice($.parameters, $.type_parameters),
              ),
            ),
          ),
          optional($._automatic_semicolon),
        ),
      ),

    opaque_modifier: $ => prec("mod", "opaque"),

    /**
     *   Extension         ::=  'extension' [DefTypeParamClause] {UsingParamClause}
     *                          '(' DefParam ')' {UsingParamClause} ExtMethods
     */
    extension_definition: $ =>
      prec.left(
        seq(
          "extension",
          field("type_parameters", optional($.type_parameters)),
          field("parameters", repeat($.parameters)),
          field(
            "body",
            choice(
              $._extension_template_body,
              $.function_definition,
              $.function_declaration,
            ),
          ),
        ),
      ),

    /**
     * GivenDef          ::=  [GivenSig] (AnnotType ['=' Expr] | StructuralInstance)
     * GivenSig          ::=  [id] [DefTypeParamClause] {UsingParamClause} ':'
     */
    given_definition: $ =>
      prec.left(
        seq(
          repeat($.annotation),
          optional($.modifiers),
          "given",
          optional($._given_constructor),
          repeat($._given_sig),
          choice(
            field("return_type", $._structural_instance),
            seq(
              field("return_type", $._annotated_type),
              optional(seq("=", field("body", $._indentable_expression))),
            ),
          ),
        ),
      ),

    _given_sig: $ => seq($._given_conditional, "=>"),

    _given_conditional: $ =>
      choice(alias($.parameters, $.given_conditional), $.type_parameters),

    _given_constructor: $ =>
      prec.right(
        seq(
          field("name", optional($._identifier)),
          field("type_parameters", optional($.type_parameters)),
          field(
            "parameters",
            repeat(seq(optional($._automatic_semicolon), $.parameters)),
          ),
          optional($._automatic_semicolon),
          ":",
        ),
      ),

    /**
     * StructuralInstance ::=  ConstrApp {'with' ConstrApp} ['with' WithTemplateBody]
     */
    _structural_instance: $ =>
      prec.left(
        PREC.compound,
        seq(
          $._constructor_application,
          choice(":", "with"),
          field("body", $.with_template_body),
        ),
      ),

    /**
     * ConstrApp         ::=  SimpleType1 {Annotation} {ParArgumentExprs}
     *
     * Note: It would look more elegant if we could make seq(choice(), optional(arguments)),
     * but that doesn't seem to work.
     */
    _constructor_application: $ =>
      prec.left(
        "constructor_application",
        choice(
          $._annotated_type,
          $.compound_type,
          // In theory structural_type should just be added to simple_type,
          // but doing so increases the state of template_body to 4000
          $._structural_type,
          // This adds _simple_type, but not the above intentionally.
          seq($._simple_type, field("arguments", $.arguments)),
          seq($._annotated_type, field("arguments", $.arguments)),
          seq($.compound_type, field("arguments", $.arguments)),
        ),
      ),

    _constructor_applications: $ =>
      prec.left(
        choice(
          commaSep1($._constructor_application),
          sep1("with", $._constructor_application),
        ),
      ),

    modifiers: $ =>
      prec.left(
        repeat1(
          prec.left(
            choice(
              "abstract",
              "final",
              "sealed",
              "implicit",
              "lazy",
              "override",
              $.access_modifier,
              $.inline_modifier,
              $.infix_modifier,
              $.into_modifier,
              $.open_modifier,
              $.tracked_modifier,
              $.transparent_modifier,
            ),
          ),
        ),
      ),

    access_modifier: $ =>
      prec.left(
        seq(choice("private", "protected"), optional($.access_qualifier)),
      ),

    access_qualifier: $ => seq("[", $._identifier, "]"),

    inline_modifier: $ => prec("mod", "inline"),
    infix_modifier: $ => prec("mod", "infix"),
    into_modifier: $ => prec("mod", "into"),
    open_modifier: $ => prec("mod", "open"),
    tracked_modifier: $ => prec("mod", "tracked"),
    transparent_modifier: $ => prec("mod", "transparent"),

    /**
     * InheritClauses    ::=  ['extends' ConstrApps] ['derives' QualId {',' QualId}]
     */
    extends_clause: $ =>
      prec.left(
        seq(
          "extends",
          field("type", $._constructor_applications),
          repeat($.arguments),
        ),
      ),

    derives_clause: $ =>
      prec.left(
        seq(
          "derives",
          commaSep1(
            field("type", choice($._type_identifier, $.stable_type_identifier)),
          ),
        ),
      ),

    class_parameters: $ =>
      prec(
        1,
        seq(
          optional($._automatic_semicolon),
          "(",
          choice(
            seq(
              "using",
              choice(
                trailingCommaSep1($.class_parameter),
                trailingCommaSep1($._param_type),
              ),
            ),
            seq(optional("implicit"), trailingCommaSep($.class_parameter)),
          ),
          ")",
        ),
      ),

    /*
     * DefParamClauses   ::=  {DefParamClause} [[nl] ‘(’ [‘implicit’] DefParams ‘)’]
     * DefParamClause    ::=  [nl] ‘(’ DefParams ‘)’ | UsingParamClause
     * DefParams         ::=  DefParam {‘,’ DefParam}
     */
    parameters: $ =>
      choice(
        seq("(", optional("implicit"), trailingCommaSep($.parameter), ")"),
        $._using_parameters_clause,
      ),

    /*
     * UsingParamClause  ::=  [nl] ‘(’ ‘using’ (DefParams | FunArgTypes) ‘)’
     * DefParams         ::=  DefParam {‘,’ DefParam}
     * FunArgTypes       ::=  FunArgType { ‘,’ FunArgType }
     */
    _using_parameters_clause: $ =>
      seq(
        "(",
        "using",
        choice(
          trailingCommaSep1($.parameter),
          trailingCommaSep1($._param_type),
        ),
        ")",
      ),

    class_parameter: $ =>
      seq(
        repeat($.annotation),
        optional($.modifiers),
        optional(choice("val", "var")),
        field("name", $._identifier),
        optional(seq(":", field("type", $._param_type))),
        optional(seq("=", field("default_value", $.expression))),
      ),

    /*
     * DefParam          ::=  {Annotation} [‘inline’] Param
     * Param             ::=  id ‘:’ ParamType [‘=’ Expr]
     */
    parameter: $ =>
      prec.left(
        PREC.control,
        seq(
          repeat($.annotation),
          optional($.inline_modifier),
          field("name", $._identifier),
          ":",
          field("type", $._param_type),
          optional(seq("=", field("default_value", $.expression))),
        ),
      ),

    /*
     * NameAndType       ::=  id ':' Type
     */
    name_and_type: $ =>
      prec.left(
        PREC.control,
        seq(field("name", $._identifier), ":", field("type", $._param_type)),
      ),

    _block: $ =>
      prec.left(
        seq(
          sep1(
            $._semicolon,
            choice($.expression, $._definition, $._end_marker, ";"),
          ),
          optional($._semicolon),
        ),
      ),

    _indentable_expression: $ =>
      prec.right(choice($.indented_block, $.indented_cases, $.expression)),

    block: $ =>
      seq(
        "{",
        optional(
          choice(
            $._block,
            alias($._block_lambda_expression, $.lambda_expression),
          ),
        ),
        "}",
      ),

    indented_block: $ =>
      prec.left(
        PREC.control,
        seq(
          $._indent,
          $._block,
          choice($._outdent, $._comma_outdent),
          optional($._end_marker),
        ),
      ),

    indented_cases: $ =>
      prec.left(
        seq(
          $._indent,
          repeat1($.case_clause),
          choice($._outdent, $._comma_outdent),
        ),
      ),

    // ---------------------------------------------------------------
    // Types

    _type: $ =>
      choice(
        $.function_type,
        $.compound_type,
        $.infix_type,
        $.match_type,
        $._annotated_type,
        $.literal_type,
        $._structural_type,
        $.type_lambda,
      ),

    _annotated_type: $ => prec.right(choice($.annotated_type, $._simple_type)),

    annotated_type: $ => prec.right(seq($._simple_type, repeat1($.annotation))),

    _simple_type: $ =>
      choice(
  
Download .txt
gitextract_igzcqol5/

├── .editorconfig
├── .envrc
├── .git-blame-ignore-revs
├── .gitattributes
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   └── bug_report.yml
│   └── workflows/
│       ├── ci.yml
│       ├── fuzz.yml
│       ├── publish.yml
│       └── sync.yml
├── .gitignore
├── .prettierrc.json
├── CMakeLists.txt
├── CONTRIBUTING.md
├── Cargo.toml
├── LICENSE
├── Makefile
├── Package.resolved
├── Package.swift
├── README.md
├── binding.gyp
├── bindings/
│   ├── c/
│   │   ├── tree-sitter-scala.h
│   │   ├── tree-sitter-scala.pc.in
│   │   └── tree_sitter/
│   │       └── tree-sitter-scala.h
│   ├── go/
│   │   ├── binding.go
│   │   └── binding_test.go
│   ├── node/
│   │   ├── binding.cc
│   │   ├── binding_test.js
│   │   ├── index.d.ts
│   │   └── index.js
│   ├── python/
│   │   ├── tests/
│   │   │   └── test_binding.py
│   │   └── tree_sitter_scala/
│   │       ├── __init__.py
│   │       ├── __init__.pyi
│   │       ├── binding.c
│   │       └── py.typed
│   ├── rust/
│   │   ├── build.rs
│   │   └── lib.rs
│   └── swift/
│       ├── TreeSitterScala/
│       │   └── scala.h
│       └── TreeSitterScalaTests/
│           └── TreeSitterScalaTests.swift
├── examples/
│   ├── Packages.scala
│   ├── PathResolver.scala
│   ├── RefChecks.scala
│   ├── SyntaxAnalyzer.scala
│   └── Variance.scala
├── go.mod
├── go.sum
├── grammar.js
├── package.json
├── pyproject.toml
├── queries/
│   ├── highlights.scm
│   ├── indents.scm
│   ├── locals.scm
│   └── tags.scm
├── script/
│   ├── parse-with-scalac
│   └── smoke_test.sh
├── setup.py
├── src/
│   ├── grammar.json
│   ├── node-types.json
│   ├── parser.c
│   ├── scanner.c
│   └── tree_sitter/
│       ├── alloc.h
│       ├── array.h
│       └── parser.h
├── test/
│   ├── corpus/
│   │   ├── annotations.txt
│   │   ├── comments.txt
│   │   ├── definitions-pending.txt
│   │   ├── definitions.txt
│   │   ├── expressions.txt
│   │   ├── literals.txt
│   │   ├── patterns-pending.txt
│   │   ├── patterns.txt
│   │   ├── types-pending.txt
│   │   └── types.txt
│   ├── highlight/
│   │   ├── basics.scala
│   │   ├── comments.scala
│   │   └── scala3.scala
│   └── tags/
│       └── basics.scala
└── tree-sitter.json
Download .txt
SYMBOL INDEX (74 symbols across 18 files)

FILE: bindings/c/tree-sitter-scala.h
  type TSLanguage (line 4) | typedef struct TSLanguage TSLanguage;

FILE: bindings/c/tree_sitter/tree-sitter-scala.h
  type TSLanguage (line 4) | typedef struct TSLanguage TSLanguage;

FILE: bindings/go/binding.go
  function Language (line 11) | func Language() unsafe.Pointer {

FILE: bindings/go/binding_test.go
  function TestCanLoadGrammar (line 10) | func TestCanLoadGrammar(t *testing.T) {

FILE: bindings/node/binding.cc
  type TSLanguage (line 3) | struct TSLanguage
  function Init (line 12) | Napi::Object Init(Napi::Env env, Napi::Object exports) {

FILE: bindings/node/index.d.ts
  type BaseNode (line 1) | type BaseNode = {
  type ChildNode (line 6) | type ChildNode = {
  type NodeInfo (line 12) | type NodeInfo =
  type Language (line 21) | type Language = {

FILE: bindings/python/tests/test_binding.py
  class TestLanguage (line 6) | class TestLanguage(TestCase):
    method test_can_load_grammar (line 7) | def test_can_load_grammar(self):

FILE: bindings/python/tree_sitter_scala/__init__.py
  function _get_query (line 8) | def _get_query(name, file):
  function __getattr__ (line 14) | def __getattr__(name):
  function __dir__ (line 30) | def __dir__():

FILE: bindings/python/tree_sitter_scala/__init__.pyi
  function language (line 6) | def language() -> object: ...

FILE: bindings/python/tree_sitter_scala/binding.c
  type TSLanguage (line 3) | typedef struct TSLanguage TSLanguage;
  function PyObject (line 7) | static PyObject* _binding_language(PyObject *Py_UNUSED(self), PyObject *...
  type PyModuleDef (line 17) | struct PyModuleDef
  function PyMODINIT_FUNC (line 25) | PyMODINIT_FUNC PyInit__binding(void) {

FILE: bindings/rust/build.rs
  function main (line 1) | fn main() {

FILE: bindings/rust/lib.rs
  function tree_sitter_scala (line 31) | fn tree_sitter_scala() -> *const ();
  constant LANGUAGE (line 37) | pub const LANGUAGE: LanguageFn = unsafe { LanguageFn::from_raw(tree_sitt...
  constant NODE_TYPES (line 42) | pub const NODE_TYPES: &str = include_str!("../../src/node-types.json");
  constant HIGHLIGHTS_QUERY (line 45) | pub const HIGHLIGHTS_QUERY: &str = include_str!("../../queries/highlight...
  constant LOCALS_QUERY (line 48) | pub const LOCALS_QUERY: &str = include_str!("../../queries/locals.scm");
  function test_can_load_grammar (line 53) | fn test_can_load_grammar() {

FILE: bindings/swift/TreeSitterScala/scala.h
  type TSLanguage (line 4) | typedef struct TSLanguage TSLanguage;

FILE: grammar.js
  constant PREC (line 1) | const PREC = {
  function commaSep (line 2066) | function commaSep(rule) {
  function commaSep1 (line 2070) | function commaSep1(rule) {
  function trailingCommaSep (line 2074) | function trailingCommaSep(rule) {
  function trailingCommaSep1 (line 2078) | function trailingCommaSep1(rule) {
  function trailingSep1 (line 2082) | function trailingSep1(delimiter, rule) {
  function sep1 (line 2086) | function sep1(delimiter, rule) {

FILE: setup.py
  class Build (line 9) | class Build(build):
    method run (line 10) | def run(self):
  class BdistWheel (line 17) | class BdistWheel(bdist_wheel):
    method get_tag (line 18) | def get_tag(self):

FILE: src/scanner.c
  type TokenType (line 15) | enum TokenType {
  type Scanner (line 62) | typedef struct {
  function tree_sitter_scala_external_scanner_destroy (line 77) | void tree_sitter_scala_external_scanner_destroy(void *payload) {
  function tree_sitter_scala_external_scanner_serialize (line 83) | unsigned tree_sitter_scala_external_scanner_serialize(void *payload, cha...
  function tree_sitter_scala_external_scanner_deserialize (line 106) | void tree_sitter_scala_external_scanner_deserialize(void *payload, const...
  function advance (line 135) | static inline void advance(TSLexer *lexer) { lexer->advance(lexer, false...
  function skip (line 137) | static inline void skip(TSLexer *lexer) { lexer->advance(lexer, true); }
  function is_op_char (line 141) | static bool is_op_char(int32_t c) {
  type StringMode (line 158) | typedef enum {
  function scan_string_content (line 164) | static bool scan_string_content(TSLexer *lexer, bool is_multiline, Strin...
  function detect_comment_start (line 228) | static bool detect_comment_start(TSLexer *lexer) {
  function scan_word (line 240) | static bool scan_word(TSLexer *lexer, const char* const word) {
  function is_leading_infix_continuation (line 255) | static bool is_leading_infix_continuation(TSLexer *lexer) {
  function debug_indents (line 287) | static inline void debug_indents(Scanner *scanner) {
  function tree_sitter_scala_external_scanner_scan (line 295) | bool tree_sitter_scala_external_scanner_scan(void *payload, TSLexer *lexer,

FILE: src/tree_sitter/array.h
  function _array__erase (line 197) | static inline void _array__erase(void* self_contents, uint32_t *size,
  function _array__swap (line 231) | static inline void _array__swap(uint32_t *self_size, uint32_t *self_capa...

FILE: src/tree_sitter/parser.h
  type TSStateId (line 17) | typedef uint16_t TSStateId;
  type TSSymbol (line 18) | typedef uint16_t TSSymbol;
  type TSFieldId (line 19) | typedef uint16_t TSFieldId;
  type TSLanguage (line 20) | typedef struct TSLanguage TSLanguage;
  type TSLanguageMetadata (line 21) | typedef struct TSLanguageMetadata {
  type TSFieldMapEntry (line 28) | typedef struct {
  type TSMapSlice (line 35) | typedef struct {
  type TSSymbolMetadata (line 40) | typedef struct {
  type TSLexer (line 46) | typedef struct TSLexer TSLexer;
  type TSLexer (line 48) | struct TSLexer {
  type TSParseActionType (line 59) | typedef enum {
  type TSParseAction (line 66) | typedef union {
  type TSLexMode (line 83) | typedef struct {
  type TSLexerMode (line 88) | typedef struct {
  type TSParseActionEntry (line 94) | typedef union {
  type TSCharacterRange (line 102) | typedef struct {
  type TSLanguage (line 107) | struct TSLanguage {
  function set_contains (line 154) | static inline bool set_contains(const TSCharacterRange *ranges, uint32_t...
Condensed preview — 77 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (908K chars).
[
  {
    "path": ".editorconfig",
    "chars": 541,
    "preview": "root = true\n\n[*]\ncharset = utf-8\n\n[*.{json,toml,yml,gyp}]\nindent_style = space\nindent_size = 2\n\n[*.js]\nindent_style = sp"
  },
  {
    "path": ".envrc",
    "chars": 8,
    "preview": "use nix\n"
  },
  {
    "path": ".git-blame-ignore-revs",
    "chars": 159,
    "preview": "# Move queries to ./queries/scala sub-directory\n889eb65aea8e0f9ce1694ab9ee528df1fa5f75d1\n\n# Formatting using Prettier\n0a"
  },
  {
    "path": ".gitattributes",
    "chars": 862,
    "preview": "* text=auto eol=lf\n\n# Generated source files\nsrc/*.json linguist-generated\nsrc/parser.c linguist-generated\nsrc/tree_sitt"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yml",
    "chars": 2215,
    "preview": "name: Bug Report\ndescription: Create an issue in tree-sitter-scala\nbody:\n  - type: input\n    id: commit\n    attributes:\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 4779,
    "preview": "name: Build/test\non:\n  push:\n  pull_request:\n    branches:\n      - master\n\njobs:\n  changedfiles:\n    runs-on: ubuntu-lat"
  },
  {
    "path": ".github/workflows/fuzz.yml",
    "chars": 323,
    "preview": "name: Fuzz Parser\n\non:\n  push:\n    branches: [master]\n    paths:\n      - src/scanner.c\n  pull_request:\n    paths:\n      "
  },
  {
    "path": ".github/workflows/publish.yml",
    "chars": 915,
    "preview": "name: Publish packages\n\non:\n  push:\n    tags: [\"*\"]\n\npermissions:\n  contents: write\n  id-token: write\n  attestations: wr"
  },
  {
    "path": ".github/workflows/sync.yml",
    "chars": 2111,
    "preview": "name: \"Check changes and sync\"\non:\n  workflow_dispatch:\n  schedule:\n    - cron: 0 5 * * *\n\njobs:\n  check-and-sync:\n    r"
  },
  {
    "path": ".gitignore",
    "chars": 392,
    "preview": "# Rust artifacts\ntarget/\n\n# Node artifacts\nbuild/\nprebuilds/\nnode_modules/\n\n# Swift artifacts\n.build/\n\n# Go artifacts\n_o"
  },
  {
    "path": ".prettierrc.json",
    "chars": 29,
    "preview": "{\n  \"arrowParens\": \"avoid\"\n}\n"
  },
  {
    "path": "CMakeLists.txt",
    "chars": 3494,
    "preview": "cmake_minimum_required(VERSION 3.13)\n\nproject(tree-sitter-scala\n        VERSION \"0.26.0\"\n        DESCRIPTION \"Scala gram"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 4618,
    "preview": "# Contributing to tree-sitter-scala\n\nFirst off, thanks for being willing to contribute to making syntax highlighting\nin "
  },
  {
    "path": "Cargo.toml",
    "chars": 684,
    "preview": "[package]\nname = \"tree-sitter-scala\"\ndescription = \"Scala grammar for tree-sitter\"\nversion = \"0.26.0\"\nauthors = [\"Max Br"
  },
  {
    "path": "LICENSE",
    "chars": 1091,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2018 Max Brunsfeld and GitHub\n\nPermission is hereby granted, free of charge, to any"
  },
  {
    "path": "Makefile",
    "chars": 3181,
    "preview": "ifeq ($(OS),Windows_NT)\n$(error Windows is not supported)\nendif\n\nLANGUAGE_NAME := tree-sitter-scala\nHOMEPAGE_URL := http"
  },
  {
    "path": "Package.resolved",
    "chars": 333,
    "preview": "{\n  \"object\": {\n    \"pins\": [\n      {\n        \"package\": \"SwiftTreeSitter\",\n        \"repositoryURL\": \"https://github.com"
  },
  {
    "path": "Package.swift",
    "chars": 1000,
    "preview": "// swift-tools-version:5.3\nimport PackageDescription\n\nlet package = Package(\n    name: \"TreeSitterScala\",\n    products: "
  },
  {
    "path": "README.md",
    "chars": 1345,
    "preview": "# tree-sitter-scala\n\n[![CI][ci]](https://github.com/tree-sitter/tree-sitter-scala/actions/workflows/ci.yml)\n[![discord]["
  },
  {
    "path": "binding.gyp",
    "chars": 600,
    "preview": "{\n  \"targets\": [\n    {\n      \"target_name\": \"tree_sitter_scala_binding\",\n      \"dependencies\": [\n        \"<!(node -p \\\"r"
  },
  {
    "path": "bindings/c/tree-sitter-scala.h",
    "chars": 242,
    "preview": "#ifndef TREE_SITTER_SCALA_H_\n#define TREE_SITTER_SCALA_H_\n\ntypedef struct TSLanguage TSLanguage;\n\n#ifdef __cplusplus\next"
  },
  {
    "path": "bindings/c/tree-sitter-scala.pc.in",
    "chars": 295,
    "preview": "prefix=@CMAKE_INSTALL_PREFIX@\nlibdir=${prefix}/@CMAKE_INSTALL_LIBDIR@\nincludedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@\n\nN"
  },
  {
    "path": "bindings/c/tree_sitter/tree-sitter-scala.h",
    "chars": 242,
    "preview": "#ifndef TREE_SITTER_SCALA_H_\n#define TREE_SITTER_SCALA_H_\n\ntypedef struct TSLanguage TSLanguage;\n\n#ifdef __cplusplus\next"
  },
  {
    "path": "bindings/go/binding.go",
    "chars": 285,
    "preview": "package tree_sitter_scala\n\n// #cgo CFLAGS: -std=c11 -fPIC\n// #include \"../../src/parser.c\"\n// #include \"../../src/scanne"
  },
  {
    "path": "bindings/go/binding_test.go",
    "chars": 359,
    "preview": "package tree_sitter_scala_test\n\nimport (\n\t\"testing\"\n\n\ttree_sitter \"github.com/tree-sitter/go-tree-sitter\"\n\ttree_sitter_s"
  },
  {
    "path": "bindings/node/binding.cc",
    "chars": 581,
    "preview": "#include <napi.h>\n\ntypedef struct TSLanguage TSLanguage;\n\nextern \"C\" TSLanguage *tree_sitter_scala();\n\n// \"tree-sitter\","
  },
  {
    "path": "bindings/node/binding_test.js",
    "chars": 250,
    "preview": "const assert = require(\"node:assert\");\nconst { test } = require(\"node:test\");\n\nconst Parser = require(\"tree-sitter\");\n\nt"
  },
  {
    "path": "bindings/node/index.d.ts",
    "chars": 452,
    "preview": "type BaseNode = {\n  type: string;\n  named: boolean;\n};\n\ntype ChildNode = {\n  multiple: boolean;\n  required: boolean;\n  t"
  },
  {
    "path": "bindings/node/index.js",
    "chars": 454,
    "preview": "const root = require(\"path\").join(__dirname, \"..\", \"..\");\n\nmodule.exports =\n  typeof process.versions.bun === \"string\"\n "
  },
  {
    "path": "bindings/python/tests/test_binding.py",
    "chars": 293,
    "preview": "from unittest import TestCase\n\nimport tree_sitter, tree_sitter_scala\n\n\nclass TestLanguage(TestCase):\n    def test_can_lo"
  },
  {
    "path": "bindings/python/tree_sitter_scala/__init__.py",
    "chars": 828,
    "preview": "\"\"\"Scala grammar for tree-sitter\"\"\"\n\nfrom importlib.resources import files as _files\n\nfrom ._binding import language\n\n\nd"
  },
  {
    "path": "bindings/python/tree_sitter_scala/__init__.pyi",
    "chars": 111,
    "preview": "from typing import Final\n\nHIGHLIGHTS_QUERY: Final[str]\nLOCALS_QUERY: Final[str]\n\ndef language() -> object: ...\n"
  },
  {
    "path": "bindings/python/tree_sitter_scala/binding.c",
    "chars": 681,
    "preview": "#include <Python.h>\n\ntypedef struct TSLanguage TSLanguage;\n\nTSLanguage *tree_sitter_scala(void);\n\nstatic PyObject* _bind"
  },
  {
    "path": "bindings/python/tree_sitter_scala/py.typed",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "bindings/rust/build.rs",
    "chars": 627,
    "preview": "fn main() {\n    let src_dir = std::path::Path::new(\"src\");\n\n    let mut c_config = cc::Build::new();\n    c_config\n      "
  },
  {
    "path": "bindings/rust/lib.rs",
    "chars": 1956,
    "preview": "//! This crate provides Scala language support for the [tree-sitter][] parsing library.\n//!\n//! Typically, you will use "
  },
  {
    "path": "bindings/swift/TreeSitterScala/scala.h",
    "chars": 242,
    "preview": "#ifndef TREE_SITTER_SCALA_H_\n#define TREE_SITTER_SCALA_H_\n\ntypedef struct TSLanguage TSLanguage;\n\n#ifdef __cplusplus\next"
  },
  {
    "path": "bindings/swift/TreeSitterScalaTests/TreeSitterScalaTests.swift",
    "chars": 363,
    "preview": "import XCTest\nimport SwiftTreeSitter\nimport TreeSitterScala\n\nfinal class TreeSitterScalaTests: XCTestCase {\n    func tes"
  },
  {
    "path": "examples/Packages.scala",
    "chars": 108,
    "preview": "package a.b\npackage c {\n  object A\n}\npackage c {\n  package object d {\n    val hello: String = \"there\"\n  }\n}\n"
  },
  {
    "path": "examples/PathResolver.scala",
    "chars": 12127,
    "preview": "/* NSC -- new Scala compiler\n * Copyright 2006-2013 LAMP/EPFL\n * @author  Paul Phillips\n */\n\npackage scala\npackage tools"
  },
  {
    "path": "examples/RefChecks.scala",
    "chars": 108853,
    "preview": "/*\n * Scala (https://www.scala-lang.org)\n *\n * Copyright EPFL and Lightbend, Inc.\n *\n * Licensed under Apache License 2."
  },
  {
    "path": "examples/SyntaxAnalyzer.scala",
    "chars": 3466,
    "preview": "/* NSC -- new Scala compiler\n * Copyright 2005-2013 LAMP/EPFL\n * @author Martin Odersky\n */\n\npackage scala.tools.nsc\npac"
  },
  {
    "path": "examples/Variance.scala",
    "chars": 25,
    "preview": "class Function1[-T1, +R]\n"
  },
  {
    "path": "go.mod",
    "chars": 168,
    "preview": "module github.com/tree-sitter/tree-sitter-scala\n\ngo 1.22\n\nrequire github.com/tree-sitter/go-tree-sitter v0.24.0\n\nrequire"
  },
  {
    "path": "go.sum",
    "chars": 4176,
    "preview": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.m"
  },
  {
    "path": "grammar.js",
    "chars": 60387,
    "preview": "const PREC = {\n  comment: 1,\n  using_directive: 2,\n  control: 1,\n  stable_type_id: 2,\n  type: 2,\n  while: 2,\n  assign: 3"
  },
  {
    "path": "package.json",
    "chars": 1167,
    "preview": "{\n  \"name\": \"tree-sitter-scala\",\n  \"version\": \"0.26.0\",\n  \"description\": \"Scala grammar for tree-sitter\",\n  \"repository\""
  },
  {
    "path": "pyproject.toml",
    "chars": 815,
    "preview": "[build-system]\nrequires = [\"setuptools>=42\", \"wheel\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"tree-si"
  },
  {
    "path": "queries/highlights.scm",
    "chars": 4345,
    "preview": "; CREDITS @stumash (stuart.mashaal@gmail.com)\n\n(field_expression field: (identifier) @property)\n(field_expression value:"
  },
  {
    "path": "queries/indents.scm",
    "chars": 439,
    "preview": "; These indent queries adhere to nvim-tree-sytter syntax.\n; See `nvim-tree-sitter-indentation-mod` vim help page.\n\n[\n  ("
  },
  {
    "path": "queries/locals.scm",
    "chars": 579,
    "preview": "(template_body) @local.scope\n(lambda_expression) @local.scope\n\n\n(function_declaration\n      name: (identifier) @local.de"
  },
  {
    "path": "queries/tags.scm",
    "chars": 1396,
    "preview": "; Definitions\n\n(package_clause\n  name: (package_identifier) @name) @definition.module\n\n(trait_definition\n  name: (identi"
  },
  {
    "path": "script/parse-with-scalac",
    "chars": 90,
    "preview": "#!/bin/bash\n\n# scalac -Yshow-trees -Xprint:parser $@\nscalac -Yshow-trees -Xprint:typer $@\n"
  },
  {
    "path": "script/smoke_test.sh",
    "chars": 3966,
    "preview": "#!/bin/bash -e\n\n# This is an integration test to generally check the quality of parsing.\n\nSCALA_SCALA_LIBRARY_EXPECTED=1"
  },
  {
    "path": "setup.py",
    "chars": 1709,
    "preview": "from os.path import isdir, join\nfrom platform import system\n\nfrom setuptools import Extension, find_packages, setup\nfrom"
  },
  {
    "path": "src/grammar.json",
    "chars": 219666,
    "preview": "{\n  \"$schema\": \"https://tree-sitter.github.io/tree-sitter/assets/schemas/grammar.schema.json\",\n  \"name\": \"scala\",\n  \"wor"
  },
  {
    "path": "src/node-types.json",
    "chars": 175763,
    "preview": "[\n  {\n    \"type\": \"_definition\",\n    \"named\": true,\n    \"subtypes\": [\n      {\n        \"type\": \"class_definition\",\n      "
  },
  {
    "path": "src/scanner.c",
    "chars": 17729,
    "preview": "#include \"tree_sitter/alloc.h\"\n#include \"tree_sitter/array.h\"\n#include \"tree_sitter/parser.h\"\n\n#include <wctype.h>\n\n// #"
  },
  {
    "path": "src/tree_sitter/alloc.h",
    "chars": 985,
    "preview": "#ifndef TREE_SITTER_ALLOC_H_\n#define TREE_SITTER_ALLOC_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <stdbool.h>\n"
  },
  {
    "path": "src/tree_sitter/array.h",
    "chars": 13269,
    "preview": "#ifndef TREE_SITTER_ARRAY_H_\n#define TREE_SITTER_ARRAY_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include \"./alloc.h\"\n"
  },
  {
    "path": "src/tree_sitter/parser.h",
    "chars": 7624,
    "preview": "#ifndef TREE_SITTER_PARSER_H_\n#define TREE_SITTER_PARSER_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <stdbool.h"
  },
  {
    "path": "test/corpus/annotations.txt",
    "chars": 2214,
    "preview": "================================\nClasses\n================================\n\n@deprecated(\"Use D\", \"1.0\") class C {}\n\n---\n\n"
  },
  {
    "path": "test/corpus/comments.txt",
    "chars": 2689,
    "preview": "================================================================================\nSingle line comments\n=================="
  },
  {
    "path": "test/corpus/definitions-pending.txt",
    "chars": 364,
    "preview": "================================================================================\nFunction without parens\n:skip\n========="
  },
  {
    "path": "test/corpus/definitions.txt",
    "chars": 51120,
    "preview": "================================================================================\nIdentifiers\n==========================="
  },
  {
    "path": "test/corpus/expressions.txt",
    "chars": 52340,
    "preview": "================================================================================\nCall expressions\n======================"
  },
  {
    "path": "test/corpus/literals.txt",
    "chars": 12742,
    "preview": "================================================================================\nSimple strings\n========================"
  },
  {
    "path": "test/corpus/patterns-pending.txt",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "test/corpus/patterns.txt",
    "chars": 10609,
    "preview": "================================================================================\nAlternative patterns\n=================="
  },
  {
    "path": "test/corpus/types-pending.txt",
    "chars": 991,
    "preview": "\n================================================================================\nSubclass with multiline params and unn"
  },
  {
    "path": "test/corpus/types.txt",
    "chars": 20816,
    "preview": "================================================================================\nStable type identifiers\n==============="
  },
  {
    "path": "test/highlight/basics.scala",
    "chars": 2277,
    "preview": "import java.time.Instant\n//^include\n//     ^namespace\n//               ^type\nobject Hello {\n// ^ keyword \n//       ^ typ"
  },
  {
    "path": "test/highlight/comments.scala",
    "chars": 153,
    "preview": "//> using scala 3.1.0\n//  ^keyword\n//        ^parameter\n//              ^string\n\n/*\n * Beep boop\n */\n// <- comment\n\n// S"
  },
  {
    "path": "test/highlight/scala3.scala",
    "chars": 2702,
    "preview": "// Optional braces syntax\nclass C:\n// ^keyword\n//    ^type\n\n  def test(aaaa: A): Int =\n  //^keyword.function\n  //  ^meth"
  },
  {
    "path": "test/tags/basics.scala",
    "chars": 1016,
    "preview": "package com.example\n//      ^definition.module\n\nenum Color:\n//   ^definition.enum\n  case Red\n  //   ^definition.class\n  "
  },
  {
    "path": "tree-sitter.json",
    "chars": 769,
    "preview": "{\n  \"grammars\": [\n    {\n      \"name\": \"scala\",\n      \"camelcase\": \"Scala\",\n      \"scope\": \"source.scala\",\n      \"path\": "
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the tree-sitter/tree-sitter-scala GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 77 files (31.7 MB), approximately 183.7k tokens, and a symbol index with 74 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!