Skip to content

feat: implement composer classmap autoloading (#49)#1563

Open
KorsarOfficial wants to merge 3 commits intoVKCOM:masterfrom
KorsarOfficial:feature/issue-49-classmap-support
Open

feat: implement composer classmap autoloading (#49)#1563
KorsarOfficial wants to merge 3 commits intoVKCOM:masterfrom
KorsarOfficial:feature/issue-49-classmap-support

Conversation

@KorsarOfficial
Copy link

@KorsarOfficial KorsarOfficial commented Mar 18, 2026

Problem

KPHP's Composer autoloader supports PSR-0, PSR-4, and autoload/files, but not autoload/classmap. Packages using classmap (common for legacy or non-PSR code) silently fail, producing class not found compile errors.

Design Decision: Reusing KPHP's Lexer

The classmap strategy requires scanning PHP files to discover which classes they declare. Rather than writing a custom parser, this implementation reuses KPHP's own lexer via php_text_to_tokens() — the same tokenizer used by the compiler pipeline.

Why the lexer and not the full parser?

The classmap scanner runs during init_composer_class_loader(), before the compilation pipeline starts. At this stage we only need class names — not full AST nodes, type inference, or semantic analysis. The lexer is the minimal sufficient tool:

  • It correctly handles all PHP syntax: strings, heredoc, block/line comments, escape sequences
  • It produces typed tokens (tok_namespace, tok_class, tok_interface, tok_trait, tok_func_name) — no fragile string matching needed
  • lexer_init() is guaranteed to run before init_composer_class_loader() in the startup sequence (compiler.cpp:202 vs :234)
  • The scanner is ~30 lines vs ~120 for a hand-rolled heuristic approach

Formal Analysis: Autoload Resolution Chain

Define the autoload resolution as a priority-ordered function:

resolve : ClassName -> FilePath | _|_

resolve(n) = PSR4(n) (+) PSR0(n) (+) CM(n) (+) Default(n)

where (f (+) g)(x) = f(x) if f(x) != _|_, else g(x)

Classmap construction — built at load time by tokenizing files from composer.json paths:

tokens(f) = php_text_to_tokens(read(f))

declarations(f) = { ns_prefix + name :
    tok_i in {tok_class, tok_interface, tok_trait},
    tok_{i+1} = tok_func_name with str_val = name }

M = Union_i { (cls, f) : f in files(p_i), cls in declarations(f) }

CM(name) = M[name] if name in dom(M), else _|_

Complexity:

  • Build: O(total_source_bytes) — one-time lexer pass at startup
  • Lookup: O(1) average (hash map) vs PSR-4's O(P*D) with filesystem probes

Implementation

File Change
compiler/data/composer-json-data.h AutoloadClassmapEntry struct + autoload_classmap vector
compiler/data/composer-json-data.cpp Parse classmap key in parse_composer_json_autoload()
compiler/composer.h classmap_lookup() method + autoload_classmap_ map
compiler/composer.cpp Token-based collect_php_class_names() via php_text_to_tokens() + scan_classmap_path() + classmap_lookup()
compiler/pipes/collect-required-and-classes.cpp Insert classmap_lookup() after psr0_lookup()

Tests

  • tests/python/tests/composer/php/test_autoload_classmap/ — fixture with classmap-based package
  • test_classmap_autoloading in test_composer.py — end-to-end build-and-compare test

Technical Report

Full report with mathematical formalization (PDF)

Closes #49

Adds support for the "classmap" key in composer.json autoload sections.
Composer's classmap autoloading lets packages map arbitrary directories
or individual .php files to classes without requiring PSR-0/4 naming
conventions.

Implementation:
- ComposerJsonData gains AutoloadClassmapEntry to hold raw paths from
  composer.json (mirroring the existing AutoloadFileItem/AutoloadPsr4Item
  pattern for JSON parsing in composer-json-data.cpp).
- ComposerAutoloader gains a new autoload_classmap_ flat map populated
  during load_file() by scanning the listed paths with a heuristic PHP
  class-declaration scanner (collect_php_class_names / scan_classmap_path
  in composer.cpp). The scanner handles namespace declarations and
  class/interface/trait/enum definitions; it uses std::filesystem for
  recursive directory traversal.
- classmap_lookup() is consulted in collect-required-and-classes.cpp
  after psr0_lookup(), completing the lookup chain: PSR-4 → PSR-0 →
  classmap → default.

Also adds:
- tests/python/tests/composer/php/test_autoload_classmap/ — fixture
  with a classmap-based package (class Logger and Api\ApiClient)
- test_classmap_autoloading in test_composer.py
…anner

The collect_php_class_names scanner had two issues:

1. Single-line block comments like /* @var int */ left in_block_comment
   set to true, causing the next line to be incorrectly skipped. Now
   checks for */ on the same line as /* before entering multi-line mode.

2. PHP # line comments were not stripped, so # class Foo would be
   incorrectly detected as a class declaration. Now strips both //
   and # comments (taking whichever appears first on the line).
Replace the heuristic line-by-line PHP class scanner with a token-based
implementation that reuses KPHP's own lexer via php_text_to_tokens().

The previous scanner manually handled block comments, line comments,
namespace parsing, and class keyword detection with ~120 lines of
fragile string matching.  The new implementation tokenizes each file
with the same lexer used by the compiler pipeline and walks the token
stream looking for tok_namespace, tok_class, tok_interface, and
tok_trait — correctly handling all PHP syntax (strings, heredoc,
comments, escape sequences) with ~30 lines of straightforward code.

lexer_init() is guaranteed to run before init_composer_class_loader()
in the compiler startup sequence (compiler.cpp:202 vs :234).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

composer support: add "autoload.classmap" support

1 participant