Steps 290-294: Phase 11a — Semanno format, annotation codegen, visitor dispatch (60/60 tests)

Semanno comment format standard (@semanno:type(key=value)) with emitter/parser
covering all 67+ annotation types. SemannoAnnotationImpl CRTP mixin provides
default visitor implementations for all 56 extended annotation methods across
7 language generators. Virtual inheritance resolves diamond ambiguity between
ProjectionGenerator and SemannoAnnotationImpl.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Bill
2026-02-13 18:41:31 +00:00
parent 8cbeef5af4
commit d4a3609050
29 changed files with 2510 additions and 17 deletions

View File

@@ -71,3 +71,5 @@ inline void collectAnnotationConflicts(const ASTNode* node,
collectAnnotationConflicts(child, out);
}
}
#include "AnnotationConflictExtended.h"

View File

@@ -234,3 +234,5 @@ private:
}
}
};
#include "AnnotationValidatorExtended.h"

View File

@@ -19,6 +19,7 @@
#include "ast/Type.h"
#include "ast/Import.h"
#include "ast/Annotation.h"
#include "ast/Serialization.h"
class CrossLanguageProjector {
public:
@@ -192,6 +193,16 @@ private:
return a;
}
// Generic clone: use Serialization roundtrip for all other annotation types
if (ct.find("Annotation") != std::string::npos ||
ct == "CapabilityRequirement" || ct == "HostCall" ||
ct == "ScheduleTask" || ct == "ModuleLoad") {
json nodeJson = toJson(anno);
nodeJson["id"] = anno->id + "_proj";
ASTNode* cloned = fromJson(nodeJson);
return cloned;
}
return nullptr;
}
@@ -535,7 +546,8 @@ private:
if (targetLanguage == "rust" || targetLanguage == "cpp" ||
targetLanguage == "java" || targetLanguage == "javascript" ||
targetLanguage == "typescript" || targetLanguage == "python" ||
targetLanguage == "elisp") {
targetLanguage == "elisp" || targetLanguage == "kotlin" ||
targetLanguage == "csharp") {
return "Tracing";
}
return strategy;
@@ -555,10 +567,9 @@ private:
// If this is an annotation node, record its type
const auto& ct = node->conceptType;
if (ct == "ReclaimAnnotation" || ct == "DeallocateAnnotation" ||
ct == "LifetimeAnnotation" || ct == "OwnerAnnotation" ||
ct == "AllocateAnnotation" || ct == "DerefStrategy" ||
ct == "OptimizationLock" || ct == "LangSpecific") {
if (ct.find("Annotation") != std::string::npos ||
ct == "DerefStrategy" || ct == "OptimizationLock" ||
ct == "LangSpecific" || ct == "CapabilityRequirement") {
types.push_back(ct);
}

View File

@@ -6,7 +6,6 @@
#include "ast/ASTNode.h"
#include "ast/Annotation.h"
#include "ast/Serialization.h"
#include <nlohmann/json.hpp>
#include <string>
#include <vector>

View File

@@ -1236,6 +1236,46 @@ private:
};
}
void registerTrainingDataTools() {
// whetstone_export_training_data
tools_.push_back({"whetstone_export_training_data",
"Export annotated code as training data for LLM fine-tuning. "
"Supports HuggingFace (instruction/input/output JSONL) and "
"PairsJSONL (raw_code/annotated_code) formats. Includes statistics.",
{{"type", "object"}, {"properties", {
{"format", {{"type", "string"},
{"description",
"Export format: 'huggingface' or 'pairs' (default: 'huggingface')"}}},
{"languages", {{"type", "array"},
{"description",
"Languages to include (default: all available)"},
{"items", {{"type", "string"}}}}}
}}}
});
toolHandlers_["whetstone_export_training_data"] =
[this](const json& args) {
return callWhetstone("exportTrainingData", args);
};
// whetstone_generate_examples
tools_.push_back({"whetstone_generate_examples",
"Generate annotated code examples with Semanno comments. "
"Takes raw source code and language, returns annotated version "
"with inferred annotations from all 8 subjects.",
{{"type", "object"}, {"properties", {
{"source", {{"type", "string"},
{"description", "Source code to annotate"}}},
{"language", {{"type", "string"},
{"description",
"Programming language (python, cpp, rust, etc.)"}}}
}}, {"required", json::array({"source", "language"})}}
});
toolHandlers_["whetstone_generate_examples"] =
[this](const json& args) {
return callWhetstone("generateExamples", args);
};
}
void registerWhetstoneTools() {
registerASTTools();
registerAnnotationTools();
@@ -1247,5 +1287,6 @@ private:
registerSidecarTools();
registerSemanticAnnotationTools();
registerEnvironmentTools();
registerTrainingDataTools();
}
};

View File

@@ -77,7 +77,8 @@ private:
// --- language-level defaults ---
if (lang == "python" || lang == "elisp" || lang == "ruby" ||
lang == "javascript" || lang == "java" || lang == "csharp") {
lang == "javascript" || lang == "java" || lang == "csharp" ||
lang == "kotlin") {
// GC languages → @Reclaim(Tracing) on the module
out.push_back({mod->id, "ReclaimAnnotation", "Tracing",
lang + " uses tracing garbage collection",

View File

@@ -110,6 +110,14 @@ public:
auto pr = TreeSitterParser::parseGoWithDiagnostics(source);
diags = std::move(pr.diagnostics);
return std::move(pr.module);
} else if (language == "kotlin") {
auto pr = TreeSitterParser::parseKotlinWithDiagnostics(source);
diags = std::move(pr.diagnostics);
return std::move(pr.module);
} else if (language == "csharp") {
auto pr = TreeSitterParser::parseCSharpWithDiagnostics(source);
diags = std::move(pr.diagnostics);
return std::move(pr.module);
}
return nullptr;
}
@@ -141,6 +149,12 @@ public:
} else if (language == "go") {
GoGenerator gen;
return gen.generate(ast);
} else if (language == "kotlin") {
KotlinGenerator gen;
return gen.generate(ast);
} else if (language == "csharp") {
CSharpGenerator gen;
return gen.generate(ast);
}
return "";
}

View File

@@ -0,0 +1,108 @@
#pragma once
// SemannoAnnotationImpl.h — CRTP mixin for Semanno annotation visitor methods
//
// Provides default implementations for all 56 extended annotation visitor
// methods defined in AnnotationVisitorExtended. Each implementation delegates
// to SemannoEmitter::emit() and prepends the language-specific comment prefix
// supplied by the Derived generator via commentPrefix().
//
// Usage:
// class PythonGenerator : public ProjectionGenerator,
// public SemannoAnnotationImpl<PythonGenerator> {
// public:
// std::string commentPrefix() const { return "# "; }
// // ... the 56 visit*() methods are inherited from the mixin ...
// };
#include "SemannoFormat.h"
#include "ast/AnnotationVisitors.h"
// CRTP mixin: Derived must provide commentPrefix() -> std::string
// Uses virtual inheritance so methods properly override the pure virtuals
// in AnnotationVisitorExtended shared with ProjectionGenerator.
template<typename Derived>
class SemannoAnnotationImpl : public virtual AnnotationVisitorExtended {
protected:
std::string semanno(const ASTNode* anno) const {
auto* self = static_cast<const Derived*>(this);
return self->commentPrefix() + SemannoEmitter::emit(anno);
}
public:
// Subject 2: Type System
std::string visitBitWidthAnnotation(const BitWidthAnnotation* a) override { return semanno(a); }
std::string visitEndianAnnotation(const EndianAnnotation* a) override { return semanno(a); }
std::string visitLayoutAnnotation(const LayoutAnnotation* a) override { return semanno(a); }
std::string visitNullabilityAnnotation(const NullabilityAnnotation* a) override { return semanno(a); }
std::string visitVarianceAnnotation(const VarianceAnnotation* a) override { return semanno(a); }
std::string visitIdentityAnnotation(const IdentityAnnotation* a) override { return semanno(a); }
std::string visitMutAnnotation(const MutAnnotation* a) override { return semanno(a); }
std::string visitTypeStateAnnotation(const TypeStateAnnotation* a) override { return semanno(a); }
// Subject 3: Concurrency
std::string visitAtomicAnnotation(const AtomicAnnotation* a) override { return semanno(a); }
std::string visitSyncAnnotation(const SyncAnnotation* a) override { return semanno(a); }
std::string visitThreadModelAnnotation(const ThreadModelAnnotation* a) override { return semanno(a); }
std::string visitMemoryBarrierAnnotation(const MemoryBarrierAnnotation* a) override { return semanno(a); }
std::string visitExecAnnotation(const ExecAnnotation* a) override { return semanno(a); }
std::string visitBlockingAnnotation(const BlockingAnnotation* a) override { return semanno(a); }
std::string visitParallelAnnotation(const ParallelAnnotation* a) override { return semanno(a); }
std::string visitTrapAnnotation(const TrapAnnotation* a) override { return semanno(a); }
std::string visitExceptionAnnotation(const ExceptionAnnotation* a) override { return semanno(a); }
std::string visitPanicAnnotation(const PanicAnnotation* a) override { return semanno(a); }
// Subject 4: Scope
std::string visitBindingAnnotation(const BindingAnnotation* a) override { return semanno(a); }
std::string visitLookupAnnotation(const LookupAnnotation* a) override { return semanno(a); }
std::string visitCaptureAnnotation(const CaptureAnnotation* a) override { return semanno(a); }
std::string visitVisibilityAnnotation(const VisibilityAnnotation* a) override { return semanno(a); }
std::string visitNamespaceAnnotation(const NamespaceAnnotation* a) override { return semanno(a); }
std::string visitScopeAnnotation(const ScopeAnnotation* a) override { return semanno(a); }
// Subject 5: Shims & Platform
std::string visitIntrinsicAnnotation(const IntrinsicAnnotation* a) override { return semanno(a); }
std::string visitRawAnnotation(const RawAnnotation* a) override { return semanno(a); }
std::string visitCallingConvAnnotation(const CallingConvAnnotation* a) override { return semanno(a); }
std::string visitLinkAnnotation(const LinkAnnotation* a) override { return semanno(a); }
std::string visitShimAnnotation(const ShimAnnotation* a) override { return semanno(a); }
std::string visitPointerArithmeticAnnotation(const PointerArithmeticAnnotation* a) override { return semanno(a); }
std::string visitOpaqueAnnotation(const OpaqueAnnotation* a) override { return semanno(a); }
std::string visitTargetAnnotation(const TargetAnnotation* a) override { return semanno(a); }
std::string visitFeatureAnnotation(const FeatureAnnotation* a) override { return semanno(a); }
std::string visitOriginalAnnotation(const OriginalAnnotation* a) override { return semanno(a); }
std::string visitMappingAnnotation(const MappingAnnotation* a) override { return semanno(a); }
// Subject 6: Optimization
std::string visitTailCallAnnotation(const TailCallAnnotation* a) override { return semanno(a); }
std::string visitLoopAnnotation(const LoopAnnotation* a) override { return semanno(a); }
std::string visitDataAnnotation(const DataAnnotation* a) override { return semanno(a); }
std::string visitAlignAnnotation(const AlignAnnotation* a) override { return semanno(a); }
std::string visitPackAnnotation(const PackAnnotation* a) override { return semanno(a); }
std::string visitBoundsCheckAnnotation(const BoundsCheckAnnotation* a) override { return semanno(a); }
std::string visitOverflowAnnotation(const OverflowAnnotation* a) override { return semanno(a); }
// Subject 7: Meta-Programming
std::string visitMetaAnnotation(const MetaAnnotation* a) override { return semanno(a); }
std::string visitSymbolAnnotation(const SymbolAnnotation* a) override { return semanno(a); }
std::string visitEvaluateAnnotation(const EvaluateAnnotation* a) override { return semanno(a); }
std::string visitTemplateAnnotation(const TemplateAnnotation* a) override { return semanno(a); }
std::string visitSyntheticAnnotation(const SyntheticAnnotation* a) override { return semanno(a); }
// Subject 8: Policy
std::string visitPolicyAnnotation(const PolicyAnnotation* a) override { return semanno(a); }
std::string visitAmbiguityAnnotation(const AmbiguityAnnotation* a) override { return semanno(a); }
std::string visitCandidateAnnotation(const CandidateAnnotation* a) override { return semanno(a); }
std::string visitTradeoffAnnotation(const TradeoffAnnotation* a) override { return semanno(a); }
std::string visitChoiceAnnotation(const ChoiceAnnotation* a) override { return semanno(a); }
std::string visitDecisionAnnotation(const DecisionAnnotation* a) override { return semanno(a); }
// Semantic Core
std::string visitIntentAnnotation(const IntentAnnotation* a) override { return semanno(a); }
std::string visitComplexityAnnotation(const ComplexityAnnotation* a) override { return semanno(a); }
std::string visitRiskAnnotation(const RiskAnnotation* a) override { return semanno(a); }
std::string visitContractAnnotation(const ContractAnnotation* a) override { return semanno(a); }
std::string visitSemanticTagAnnotation(const SemanticTagAnnotation* a) override { return semanno(a); }
// Environment
std::string visitCapabilityRequirement(const CapabilityRequirement* a) override { return semanno(a); }
};

614
editor/src/SemannoFormat.h Normal file
View File

@@ -0,0 +1,614 @@
#pragma once
// SemannoFormat.h — Semanno inline comment format standard
//
// Format: @semanno:type(key=value,key2=value2)
//
// SemannoEmitter — converts annotation ASTNodes to Semanno comment strings
// SemannoParser — parses Semanno comment strings back to structured data
//
// Covers all 67+ annotation types defined in Annotation.h and EnvironmentSpec.h.
#include "ast/ASTNode.h"
#include "ast/Annotation.h"
#include "EnvironmentSpec.h"
#include <string>
#include <map>
#include <vector>
#include <sstream>
#include <algorithm>
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
namespace semanno_detail {
inline std::string escapeValue(const std::string& v) {
std::string out;
out.reserve(v.size() + 2);
for (char c : v) {
if (c == '"') out += "\\\"";
else if (c == '\\') out += "\\\\";
else out += c;
}
return out;
}
inline std::string unescapeValue(const std::string& v) {
std::string out;
out.reserve(v.size());
for (size_t i = 0; i < v.size(); ++i) {
if (v[i] == '\\' && i + 1 < v.size()) {
if (v[i + 1] == '"') { out += '"'; ++i; }
else if (v[i + 1] == '\\') { out += '\\'; ++i; }
else out += v[i];
} else {
out += v[i];
}
}
return out;
}
inline std::string joinVec(const std::vector<std::string>& vec) {
std::string out;
for (size_t i = 0; i < vec.size(); ++i) {
if (i > 0) out += ";";
out += escapeValue(vec[i]);
}
return out;
}
inline std::vector<std::string> splitVec(const std::string& s) {
std::vector<std::string> out;
if (s.empty()) return out;
std::string cur;
for (size_t i = 0; i < s.size(); ++i) {
if (s[i] == '\\' && i + 1 < s.size()) {
cur += s[i];
cur += s[i + 1];
++i;
} else if (s[i] == ';') {
out.push_back(unescapeValue(cur));
cur.clear();
} else {
cur += s[i];
}
}
out.push_back(unescapeValue(cur));
return out;
}
// Build "key=\"value\"" pair; omits the pair entirely when value is empty.
inline void appendProp(std::string& buf, const std::string& key,
const std::string& val, bool& first) {
if (val.empty()) return;
if (!first) buf += ",";
first = false;
buf += key + "=\"" + escapeValue(val) + "\"";
}
inline void appendInt(std::string& buf, const std::string& key,
int val, bool& first) {
if (!first) buf += ",";
first = false;
buf += key + "=" + std::to_string(val);
}
inline void appendBool(std::string& buf, const std::string& key,
bool val, bool& first) {
if (!first) buf += ",";
first = false;
buf += key + "=" + (val ? "true" : "false");
}
inline void appendVec(std::string& buf, const std::string& key,
const std::vector<std::string>& vec, bool& first) {
if (vec.empty()) return;
if (!first) buf += ",";
first = false;
buf += key + "=\"" + joinVec(vec) + "\"";
}
} // namespace semanno_detail
// ---------------------------------------------------------------------------
// SemannoEmitter
// ---------------------------------------------------------------------------
class SemannoEmitter {
public:
/// Returns "@semanno:type(key=value,...)" or empty string if unrecognised.
static std::string emit(const ASTNode* anno) {
if (!anno) return "";
const std::string& ct = anno->conceptType;
std::string tag;
std::string props;
bool first = true;
using namespace semanno_detail;
// --- Subject 1: Memory ---
if (ct == "DeallocateAnnotation") {
tag = "deallocate";
auto* a = static_cast<const DeallocateAnnotation*>(anno);
appendProp(props, "strategy", a->strategy, first);
appendProp(props, "deallocateLocation", a->deallocateLocation, first);
appendProp(props, "owner", a->owner, first);
} else if (ct == "LifetimeAnnotation") {
tag = "lifetime";
auto* a = static_cast<const LifetimeAnnotation*>(anno);
appendProp(props, "strategy", a->strategy, first);
appendProp(props, "lifetimeScope", a->lifetimeScope, first);
} else if (ct == "ReclaimAnnotation") {
tag = "reclaim";
auto* a = static_cast<const ReclaimAnnotation*>(anno);
appendProp(props, "strategy", a->strategy, first);
appendProp(props, "reclaimPattern", a->reclaimPattern, first);
} else if (ct == "OwnerAnnotation") {
tag = "owner";
auto* a = static_cast<const OwnerAnnotation*>(anno);
appendProp(props, "strategy", a->strategy, first);
appendProp(props, "ownerType", a->ownerType, first);
} else if (ct == "AllocateAnnotation") {
tag = "allocate";
auto* a = static_cast<const AllocateAnnotation*>(anno);
appendProp(props, "strategy", a->strategy, first);
appendProp(props, "allocationPattern", a->allocationPattern, first);
} else if (ct == "HotColdAnnotation") {
tag = "hotcold";
auto* a = static_cast<const HotColdAnnotation*>(anno);
appendProp(props, "hint", a->hint, first);
} else if (ct == "InlineAnnotation") {
tag = "inline";
auto* a = static_cast<const InlineAnnotation*>(anno);
appendProp(props, "mode", a->mode, first);
} else if (ct == "PureAnnotation") {
tag = "pure";
} else if (ct == "ConstExprAnnotation") {
tag = "constexpr";
} else if (ct == "DerefStrategy") {
tag = "deref";
auto* a = static_cast<const DerefStrategy*>(anno);
appendProp(props, "strategy", a->strategy, first);
} else if (ct == "OptimizationLock") {
tag = "optlock";
auto* a = static_cast<const OptimizationLock*>(anno);
appendProp(props, "lockedBy", a->lockedBy, first);
appendProp(props, "lockReason", a->lockReason, first);
appendProp(props, "lockLevel", a->lockLevel, first);
} else if (ct == "LangSpecific") {
tag = "langspecific";
auto* a = static_cast<const LangSpecific*>(anno);
appendProp(props, "language", a->language, first);
appendProp(props, "idiomType", a->idiomType, first);
// --- Subject 2: Type System ---
} else if (ct == "BitWidthAnnotation") {
tag = "bitwidth";
auto* a = static_cast<const BitWidthAnnotation*>(anno);
appendInt(props, "width", a->width, first);
} else if (ct == "EndianAnnotation") {
tag = "endian";
auto* a = static_cast<const EndianAnnotation*>(anno);
appendProp(props, "order", a->order, first);
} else if (ct == "LayoutAnnotation") {
tag = "layout";
auto* a = static_cast<const LayoutAnnotation*>(anno);
appendProp(props, "mode", a->mode, first);
appendInt(props, "alignment", a->alignment, first);
} else if (ct == "NullabilityAnnotation") {
tag = "nullability";
auto* a = static_cast<const NullabilityAnnotation*>(anno);
appendBool(props, "nullable", a->nullable, first);
appendProp(props, "strategy", a->strategy, first);
} else if (ct == "VarianceAnnotation") {
tag = "variance";
auto* a = static_cast<const VarianceAnnotation*>(anno);
appendProp(props, "variance", a->variance, first);
} else if (ct == "IdentityAnnotation") {
tag = "identity";
auto* a = static_cast<const IdentityAnnotation*>(anno);
appendProp(props, "mode", a->mode, first);
} else if (ct == "MutAnnotation") {
tag = "mut";
auto* a = static_cast<const MutAnnotation*>(anno);
appendProp(props, "depth", a->depth, first);
} else if (ct == "TypeStateAnnotation") {
tag = "typestate";
auto* a = static_cast<const TypeStateAnnotation*>(anno);
appendProp(props, "state", a->state, first);
// --- Subject 3: Concurrency ---
} else if (ct == "AtomicAnnotation") {
tag = "atomic";
auto* a = static_cast<const AtomicAnnotation*>(anno);
appendProp(props, "consistency", a->consistency, first);
} else if (ct == "SyncAnnotation") {
tag = "sync";
auto* a = static_cast<const SyncAnnotation*>(anno);
appendProp(props, "primitive", a->primitive, first);
} else if (ct == "ThreadModelAnnotation") {
tag = "threadmodel";
auto* a = static_cast<const ThreadModelAnnotation*>(anno);
appendProp(props, "model", a->model, first);
} else if (ct == "MemoryBarrierAnnotation") {
tag = "memorybarrier";
} else if (ct == "ExecAnnotation") {
tag = "exec";
auto* a = static_cast<const ExecAnnotation*>(anno);
appendProp(props, "mode", a->mode, first);
appendProp(props, "runtimeHint", a->runtimeHint, first);
} else if (ct == "BlockingAnnotation") {
tag = "blocking";
auto* a = static_cast<const BlockingAnnotation*>(anno);
appendProp(props, "kind", a->kind, first);
} else if (ct == "ParallelAnnotation") {
tag = "parallel";
auto* a = static_cast<const ParallelAnnotation*>(anno);
appendProp(props, "kind", a->kind, first);
} else if (ct == "TrapAnnotation") {
tag = "trap";
auto* a = static_cast<const TrapAnnotation*>(anno);
appendProp(props, "signal", a->signal, first);
} else if (ct == "ExceptionAnnotation") {
tag = "exception";
auto* a = static_cast<const ExceptionAnnotation*>(anno);
appendProp(props, "style", a->style, first);
} else if (ct == "PanicAnnotation") {
tag = "panic";
auto* a = static_cast<const PanicAnnotation*>(anno);
appendProp(props, "behavior", a->behavior, first);
// --- Subject 4: Scope ---
} else if (ct == "BindingAnnotation") {
tag = "binding";
auto* a = static_cast<const BindingAnnotation*>(anno);
appendProp(props, "time", a->time, first);
} else if (ct == "LookupAnnotation") {
tag = "lookup";
auto* a = static_cast<const LookupAnnotation*>(anno);
appendProp(props, "mode", a->mode, first);
} else if (ct == "CaptureAnnotation") {
tag = "capture";
auto* a = static_cast<const CaptureAnnotation*>(anno);
appendProp(props, "strategy", a->strategy, first);
} else if (ct == "VisibilityAnnotation") {
tag = "visibility";
auto* a = static_cast<const VisibilityAnnotation*>(anno);
appendProp(props, "level", a->level, first);
} else if (ct == "NamespaceAnnotation") {
tag = "namespace";
auto* a = static_cast<const NamespaceAnnotation*>(anno);
appendProp(props, "style", a->style, first);
} else if (ct == "ScopeAnnotation") {
tag = "scope";
auto* a = static_cast<const ScopeAnnotation*>(anno);
appendProp(props, "kind", a->kind, first);
// --- Subject 5: Shims ---
} else if (ct == "IntrinsicAnnotation") {
tag = "intrinsic";
auto* a = static_cast<const IntrinsicAnnotation*>(anno);
appendProp(props, "instruction", a->instruction, first);
appendProp(props, "arch", a->arch, first);
} else if (ct == "RawAnnotation") {
tag = "raw";
auto* a = static_cast<const RawAnnotation*>(anno);
appendProp(props, "language", a->language, first);
appendProp(props, "code", a->code, first);
} else if (ct == "CallingConvAnnotation") {
tag = "callingconv";
auto* a = static_cast<const CallingConvAnnotation*>(anno);
appendProp(props, "convention", a->convention, first);
} else if (ct == "LinkAnnotation") {
tag = "link";
auto* a = static_cast<const LinkAnnotation*>(anno);
appendProp(props, "symbolName", a->symbolName, first);
appendProp(props, "library", a->library, first);
} else if (ct == "ShimAnnotation") {
tag = "shim";
auto* a = static_cast<const ShimAnnotation*>(anno);
appendProp(props, "strategy", a->strategy, first);
} else if (ct == "PointerArithmeticAnnotation") {
tag = "pointerarith";
} else if (ct == "OpaqueAnnotation") {
tag = "opaque";
auto* a = static_cast<const OpaqueAnnotation*>(anno);
appendProp(props, "reason", a->reason, first);
} else if (ct == "TargetAnnotation") {
tag = "target";
auto* a = static_cast<const TargetAnnotation*>(anno);
appendProp(props, "platform", a->platform, first);
appendProp(props, "arch", a->arch, first);
} else if (ct == "FeatureAnnotation") {
tag = "feature";
auto* a = static_cast<const FeatureAnnotation*>(anno);
appendProp(props, "flag", a->flag, first);
appendBool(props, "enabled", a->enabled, first);
} else if (ct == "OriginalAnnotation") {
tag = "original";
auto* a = static_cast<const OriginalAnnotation*>(anno);
appendProp(props, "sourceCode", a->sourceCode, first);
appendProp(props, "sourceLanguage", a->sourceLanguage, first);
} else if (ct == "MappingAnnotation") {
tag = "mapping";
auto* a = static_cast<const MappingAnnotation*>(anno);
appendVec(props, "history", a->history, first);
// --- Subject 6: Optimization ---
} else if (ct == "TailCallAnnotation") {
tag = "tailcall";
} else if (ct == "LoopAnnotation") {
tag = "loop";
auto* a = static_cast<const LoopAnnotation*>(anno);
appendProp(props, "hint", a->hint, first);
appendInt(props, "factor", a->factor, first);
} else if (ct == "DataAnnotation") {
tag = "data";
auto* a = static_cast<const DataAnnotation*>(anno);
appendProp(props, "hint", a->hint, first);
} else if (ct == "AlignAnnotation") {
tag = "align";
auto* a = static_cast<const AlignAnnotation*>(anno);
appendInt(props, "bytes", a->bytes, first);
} else if (ct == "PackAnnotation") {
tag = "pack";
} else if (ct == "BoundsCheckAnnotation") {
tag = "boundscheck";
auto* a = static_cast<const BoundsCheckAnnotation*>(anno);
appendBool(props, "enabled", a->enabled, first);
} else if (ct == "OverflowAnnotation") {
tag = "overflow";
auto* a = static_cast<const OverflowAnnotation*>(anno);
appendProp(props, "behavior", a->behavior, first);
// --- Subject 7: Meta-Programming ---
} else if (ct == "MetaAnnotation") {
tag = "meta";
auto* a = static_cast<const MetaAnnotation*>(anno);
appendProp(props, "state", a->state, first);
appendProp(props, "phase", a->phase, first);
} else if (ct == "SymbolAnnotation") {
tag = "symbol";
auto* a = static_cast<const SymbolAnnotation*>(anno);
appendProp(props, "mode", a->mode, first);
} else if (ct == "EvaluateAnnotation") {
tag = "evaluate";
auto* a = static_cast<const EvaluateAnnotation*>(anno);
appendProp(props, "phase", a->phase, first);
} else if (ct == "TemplateAnnotation") {
tag = "template";
auto* a = static_cast<const TemplateAnnotation*>(anno);
appendProp(props, "specialization", a->specialization, first);
} else if (ct == "SyntheticAnnotation") {
tag = "synthetic";
auto* a = static_cast<const SyntheticAnnotation*>(anno);
appendProp(props, "generator", a->generator, first);
appendBool(props, "isStructuralRisk", a->isStructuralRisk, first);
// --- Subject 8: Policy ---
} else if (ct == "PolicyAnnotation") {
tag = "policy";
auto* a = static_cast<const PolicyAnnotation*>(anno);
appendProp(props, "strictness", a->strictness, first);
appendProp(props, "perf", a->perf, first);
appendProp(props, "style", a->style, first);
appendBool(props, "binaryStable", a->binaryStable, first);
} else if (ct == "AmbiguityAnnotation") {
tag = "ambiguity";
auto* a = static_cast<const AmbiguityAnnotation*>(anno);
appendProp(props, "intent", a->intent, first);
appendVec(props, "options", a->options, first);
} else if (ct == "CandidateAnnotation") {
tag = "candidate";
auto* a = static_cast<const CandidateAnnotation*>(anno);
appendVec(props, "inferredTypes", a->inferredTypes, first);
} else if (ct == "TradeoffAnnotation") {
tag = "tradeoff";
auto* a = static_cast<const TradeoffAnnotation*>(anno);
appendProp(props, "reason", a->reason, first);
appendProp(props, "safetyCost", a->safetyCost, first);
appendProp(props, "perfCost", a->perfCost, first);
} else if (ct == "ChoiceAnnotation") {
tag = "choice";
auto* a = static_cast<const ChoiceAnnotation*>(anno);
appendProp(props, "choiceId", a->choiceId, first);
appendVec(props, "options", a->options, first);
} else if (ct == "DecisionAnnotation") {
tag = "decision";
auto* a = static_cast<const DecisionAnnotation*>(anno);
appendProp(props, "choiceId", a->choiceId, first);
appendProp(props, "selection", a->selection, first);
appendProp(props, "author", a->author, first);
appendProp(props, "reason", a->reason, first);
// --- Semantic Core ---
} else if (ct == "IntentAnnotation") {
tag = "intent";
auto* a = static_cast<const IntentAnnotation*>(anno);
appendProp(props, "summary", a->summary, first);
appendProp(props, "category", a->category, first);
} else if (ct == "ComplexityAnnotation") {
tag = "complexity";
auto* a = static_cast<const ComplexityAnnotation*>(anno);
appendProp(props, "timeComplexity", a->timeComplexity, first);
appendInt(props, "cognitiveComplexity", a->cognitiveComplexity, first);
appendInt(props, "linesOfLogic", a->linesOfLogic, first);
} else if (ct == "RiskAnnotation") {
tag = "risk";
auto* a = static_cast<const RiskAnnotation*>(anno);
appendProp(props, "level", a->level, first);
appendProp(props, "reason", a->reason, first);
appendInt(props, "dependentCount", a->dependentCount, first);
} else if (ct == "ContractAnnotation") {
tag = "contract";
auto* a = static_cast<const ContractAnnotation*>(anno);
appendProp(props, "preconditions", a->preconditions, first);
appendProp(props, "postconditions", a->postconditions, first);
appendProp(props, "returnShape", a->returnShape, first);
appendProp(props, "sideEffects", a->sideEffects, first);
} else if (ct == "SemanticTagAnnotation") {
tag = "tags";
auto* a = static_cast<const SemanticTagAnnotation*>(anno);
appendVec(props, "tags", a->tags, first);
// --- Environment ---
} else if (ct == "CapabilityRequirement") {
tag = "capability";
auto* a = static_cast<const CapabilityRequirement*>(anno);
appendProp(props, "capability", a->capability, first);
appendBool(props, "required", a->required, first);
} else {
return ""; // unrecognised annotation type
}
// Assemble final string
if (props.empty())
return "@semanno:" + tag;
return "@semanno:" + tag + "(" + props + ")";
}
};
// ---------------------------------------------------------------------------
// SemannoParser
// ---------------------------------------------------------------------------
struct SemannoEntry {
std::string type; // e.g. "intent"
std::map<std::string, std::string> properties; // key→raw value string
};
class SemannoParser {
public:
/// Check whether a line contains a Semanno annotation.
static bool isSemannoComment(const std::string& line) {
return line.find("@semanno:") != std::string::npos;
}
/// Parse a single Semanno comment line.
/// Accepts lines with any comment prefix: "//", "#", "/*", "--", etc.
/// Returns a SemannoEntry with type and key-value properties.
static SemannoEntry parse(const std::string& line) {
SemannoEntry entry;
// Locate the "@semanno:" marker
auto pos = line.find("@semanno:");
if (pos == std::string::npos) return entry;
pos += 9; // skip past "@semanno:"
// Extract the type name (until '(' or end of relevant content)
size_t typeEnd = pos;
while (typeEnd < line.size() && line[typeEnd] != '(' &&
line[typeEnd] != ')' && line[typeEnd] != ' ' &&
line[typeEnd] != '\t' && line[typeEnd] != '\n' &&
line[typeEnd] != '\r') {
++typeEnd;
}
entry.type = line.substr(pos, typeEnd - pos);
// Strip any trailing comment close markers from type (e.g. "*/" )
while (!entry.type.empty() &&
(entry.type.back() == '*' || entry.type.back() == '/')) {
entry.type.pop_back();
}
// If there is no property block, we are done.
if (typeEnd >= line.size() || line[typeEnd] != '(') return entry;
// Find the matching closing paren (respecting escaped quotes).
size_t propStart = typeEnd + 1;
size_t propEnd = findMatchingParen(line, propStart);
if (propEnd == std::string::npos) propEnd = line.size();
std::string propBlock = line.substr(propStart, propEnd - propStart);
parseProperties(propBlock, entry.properties);
return entry;
}
private:
/// Find the closing ')' that matches an opening '(' at `start`,
/// respecting quoted strings.
static size_t findMatchingParen(const std::string& s, size_t start) {
bool inQuote = false;
for (size_t i = start; i < s.size(); ++i) {
if (s[i] == '\\' && i + 1 < s.size()) {
++i; // skip escaped char
continue;
}
if (s[i] == '"') {
inQuote = !inQuote;
} else if (s[i] == ')' && !inQuote) {
return i;
}
}
return std::string::npos;
}
/// Parse "key=\"value\",key2=value2,..." into a map.
static void parseProperties(const std::string& block,
std::map<std::string, std::string>& props) {
size_t i = 0;
while (i < block.size()) {
// Skip whitespace
while (i < block.size() && (block[i] == ' ' || block[i] == '\t'))
++i;
if (i >= block.size()) break;
// Read key (up to '=')
size_t keyStart = i;
while (i < block.size() && block[i] != '=') ++i;
if (i >= block.size()) break;
std::string key = block.substr(keyStart, i - keyStart);
// Trim trailing whitespace from key
while (!key.empty() && (key.back() == ' ' || key.back() == '\t'))
key.pop_back();
++i; // skip '='
// Skip whitespace after '='
while (i < block.size() && (block[i] == ' ' || block[i] == '\t'))
++i;
std::string value;
if (i < block.size() && block[i] == '"') {
// Quoted value — read until unescaped closing '"'
++i; // skip opening '"'
while (i < block.size()) {
if (block[i] == '\\' && i + 1 < block.size()) {
value += block[i];
value += block[i + 1];
i += 2;
} else if (block[i] == '"') {
++i; // skip closing '"'
break;
} else {
value += block[i];
++i;
}
}
// Unescape the value
value = semanno_detail::unescapeValue(value);
} else {
// Unquoted value — read until ',' or end
size_t valStart = i;
while (i < block.size() && block[i] != ',') ++i;
value = block.substr(valStart, i - valStart);
// Trim trailing whitespace
while (!value.empty() &&
(value.back() == ' ' || value.back() == '\t'))
value.pop_back();
}
props[key] = value;
// Skip comma separator
if (i < block.size() && block[i] == ',') ++i;
}
}
};
// end of SemannoFormat.h

View File

@@ -87,7 +87,11 @@ enum class ScenarioType {
CrossLanguage,
Refactor,
SecurityAudit,
MultiStepDebug
MultiStepDebug,
AnnotateAllSubjects,
ValidateAndFix,
SemannoExport,
CrossLanguageAnnotated
};
struct ScenarioParams {
@@ -136,6 +140,26 @@ static std::vector<CodeSample> getBuiltinCorpus() {
// Rust samples
{"rust", "fn binary_search(arr: &[i32], target: i32) -> Option<usize> {\n let mut low = 0;\n let mut high = arr.len();\n while low < high {\n let mid = low + (high - low) / 2;\n if arr[mid] == target { return Some(mid); }\n if arr[mid] < target { low = mid + 1; }\n else { high = mid; }\n }\n None\n}\n",
"Binary search implementation", 2},
// Kotlin samples
{"kotlin", "fun greet(name: String): String {\n return \"Hello, $name!\"\n}\n\nfun sum(a: Int, b: Int): Int = a + b\n",
"Simple Kotlin functions", 1},
{"kotlin", "data class Point(val x: Double, val y: Double)\n\nfun distance(a: Point, b: Point): Double {\n val dx = a.x - b.x\n val dy = a.y - b.y\n return Math.sqrt(dx * dx + dy * dy)\n}\n",
"Kotlin data class and math", 2},
// C# samples
{"csharp", "public class Calculator {\n public int Add(int a, int b) {\n return a + b;\n }\n public int Multiply(int a, int b) {\n return a * b;\n }\n}\n",
"Simple C# calculator class", 1},
{"csharp", "using System.Collections.Generic;\n\npublic class Stack<T> {\n private List<T> items = new List<T>();\n public void Push(T item) { items.Add(item); }\n public T Pop() { var item = items[items.Count - 1]; items.RemoveAt(items.Count - 1); return item; }\n public int Count => items.Count;\n}\n",
"Generic stack implementation", 2},
// Go samples
{"go", "package main\n\nfunc fibonacci(n int) int {\n if n <= 1 {\n return n\n }\n return fibonacci(n-1) + fibonacci(n-2)\n}\n",
"Recursive fibonacci", 1},
// Java samples
{"java", "public class StringUtils {\n public static String reverse(String s) {\n return new StringBuilder(s).reverse().toString();\n }\n public static boolean isPalindrome(String s) {\n String rev = reverse(s);\n return s.equals(rev);\n }\n}\n",
"String utility methods", 1},
};
}
@@ -166,6 +190,14 @@ public:
return generateSecurityAudit(params);
case ScenarioType::MultiStepDebug:
return generateMultiStepDebug(params);
case ScenarioType::AnnotateAllSubjects:
return generateAnnotateAllSubjects(params);
case ScenarioType::ValidateAndFix:
return generateValidateAndFix(params);
case ScenarioType::SemannoExport:
return generateSemannoExport(params);
case ScenarioType::CrossLanguageAnnotated:
return generateCrossLanguageAnnotated(params);
}
return {};
}
@@ -179,7 +211,11 @@ public:
ScenarioType::CrossLanguage,
ScenarioType::Refactor,
ScenarioType::SecurityAudit,
ScenarioType::MultiStepDebug
ScenarioType::MultiStepDebug,
ScenarioType::AnnotateAllSubjects,
ScenarioType::ValidateAndFix,
ScenarioType::SemannoExport,
ScenarioType::CrossLanguageAnnotated
};
for (int i = 0; i < count; ++i) {
@@ -482,6 +518,127 @@ private:
return trace;
}
// --- Scenario: Annotate All Subjects ---
Trace generateAnnotateAllSubjects(const ScenarioParams& params) {
Trace trace;
trace.id = nextId();
trace.scenario = "annotate_all_subjects";
trace.difficulty = "advanced";
trace.language = params.language;
const auto& sample = pickSample(params.language);
trace.steps.push_back({"user",
"Add annotations from all 8 subjects (memory, type system, concurrency, "
"scope, shims, optimization, meta-programming, policy) to this code.", "", {}, {}});
trace.steps.push_back({"assistant",
"I'll analyze the code and apply annotations across all subject areas.", "", {}, {}});
json astResult = simulateGetAST(sample.source, params.language);
trace.steps.push_back({"tool_call", "", "whetstone_get_ast", json::object(), {}});
trace.steps.push_back({"tool_result", "", "whetstone_get_ast", {}, astResult});
trace.toolCallCount += 1;
addToolUsed(trace, "whetstone_get_ast");
trace.steps.push_back({"assistant",
"Applied annotations: @Reclaim(Tracing), @BitWidth(64), @Exec(sync), "
"@Visibility(public), @TailCall, @Policy(strict). All 8 subjects covered.", "", {}, {}});
return trace;
}
// --- Scenario: Validate and Fix ---
Trace generateValidateAndFix(const ScenarioParams& params) {
Trace trace;
trace.id = nextId();
trace.scenario = "validate_and_fix";
trace.difficulty = "intermediate";
trace.language = params.language;
trace.steps.push_back({"user",
"Validate all annotations and fix any conflicts or errors.", "", {}, {}});
trace.steps.push_back({"assistant",
"I'll run validation and conflict detection, then fix issues.", "", {}, {}});
json suggestResult = {
{"scopeId", "mod1"},
{"suggestions", json::array()},
{"diagnostics", json::array({{
{"severity", "error"},
{"message", "E0700: @Pure conflicts with @Blocking"},
{"nodeId", "fn1"}
}})}
};
trace.steps.push_back({"tool_call", "", "whetstone_suggest_annotations", json::object(), {}});
trace.steps.push_back({"tool_result", "", "whetstone_suggest_annotations", {}, suggestResult});
trace.toolCallCount += 1;
addToolUsed(trace, "whetstone_suggest_annotations");
trace.steps.push_back({"assistant",
"Found conflict E0700: @Pure vs @Blocking. Removed @Blocking to resolve.", "", {}, {}});
return trace;
}
// --- Scenario: Semanno Export ---
Trace generateSemannoExport(const ScenarioParams& params) {
Trace trace;
trace.id = nextId();
trace.scenario = "semanno_export";
trace.difficulty = "basic";
trace.language = params.language;
trace.steps.push_back({"user",
"Export the annotated code with Semanno inline comments.", "", {}, {}});
trace.steps.push_back({"assistant",
"I'll generate code with @semanno inline comments for all annotations.", "", {}, {}});
const auto& sample = pickSample(params.language);
json pipelineResult = {
{"success", true},
{"generatedCode", "// @semanno:intent(summary=\"math helpers\")\n" + sample.source},
{"parseDiagnostics", json::array()},
{"validationDiagnostics", json::array()},
{"violations", json::array()},
{"suggestions", json::array()},
{"foldCount", 0}, {"dceCount", 0}
};
trace.steps.push_back({"tool_call", "", "whetstone_run_pipeline",
{{"source", sample.source}, {"sourceLanguage", params.language},
{"targetLanguage", params.language}}, {}});
trace.steps.push_back({"tool_result", "", "whetstone_run_pipeline", {}, pipelineResult});
trace.toolCallCount += 1;
addToolUsed(trace, "whetstone_run_pipeline");
trace.steps.push_back({"assistant",
"Exported code with Semanno comments. All annotations are now "
"embedded as parseable inline comments.", "", {}, {}});
return trace;
}
// --- Scenario: Cross-Language Annotated ---
Trace generateCrossLanguageAnnotated(const ScenarioParams& params) {
Trace trace;
trace.id = nextId();
trace.scenario = "cross_language_annotated";
trace.difficulty = "advanced";
trace.language = params.language;
std::string target = (params.language == "python") ? "kotlin" :
(params.language == "kotlin") ? "csharp" : "python";
trace.steps.push_back({"user",
"Project this annotated " + params.language + " code to " + target +
", preserving all semantic annotations.", "", {}, {}});
trace.steps.push_back({"assistant",
"I'll project to " + target + " while ensuring annotations are preserved.", "", {}, {}});
json pipelineResult = {
{"success", true},
{"generatedCode", "// Generated annotated " + target + " code"},
{"parseDiagnostics", json::array()},
{"validationDiagnostics", json::array()},
{"violations", json::array()},
{"suggestions", json::array()},
{"foldCount", 0}, {"dceCount", 0}
};
trace.steps.push_back({"tool_call", "", "whetstone_run_pipeline",
{{"source", pickSample(params.language).source},
{"sourceLanguage", params.language}, {"targetLanguage", target}}, {}});
trace.steps.push_back({"tool_result", "", "whetstone_run_pipeline", {}, pipelineResult});
trace.toolCallCount += 1;
addToolUsed(trace, "whetstone_run_pipeline");
trace.steps.push_back({"assistant",
"Successfully projected to " + target + " with all annotations preserved. "
"Semanno comments are language-appropriate.", "", {}, {}});
return trace;
}
// Simulate getAST result for a code sample
json simulateGetAST(const std::string& source, const std::string& language) {
// Use real parser if possible, fall back to mock

View File

@@ -0,0 +1,87 @@
#pragma once
#include "Annotation.h"
#include "../EnvironmentSpec.h"
// Pure virtual interface for Subject 2-8 annotation visitors.
// Generators that support these annotations inherit from this.
class AnnotationVisitorExtended {
public:
virtual ~AnnotationVisitorExtended() = default;
// Subject 2: Type System
virtual std::string visitBitWidthAnnotation(const BitWidthAnnotation*) = 0;
virtual std::string visitEndianAnnotation(const EndianAnnotation*) = 0;
virtual std::string visitLayoutAnnotation(const LayoutAnnotation*) = 0;
virtual std::string visitNullabilityAnnotation(const NullabilityAnnotation*) = 0;
virtual std::string visitVarianceAnnotation(const VarianceAnnotation*) = 0;
virtual std::string visitIdentityAnnotation(const IdentityAnnotation*) = 0;
virtual std::string visitMutAnnotation(const MutAnnotation*) = 0;
virtual std::string visitTypeStateAnnotation(const TypeStateAnnotation*) = 0;
// Subject 3: Concurrency
virtual std::string visitAtomicAnnotation(const AtomicAnnotation*) = 0;
virtual std::string visitSyncAnnotation(const SyncAnnotation*) = 0;
virtual std::string visitThreadModelAnnotation(const ThreadModelAnnotation*) = 0;
virtual std::string visitMemoryBarrierAnnotation(const MemoryBarrierAnnotation*) = 0;
virtual std::string visitExecAnnotation(const ExecAnnotation*) = 0;
virtual std::string visitBlockingAnnotation(const BlockingAnnotation*) = 0;
virtual std::string visitParallelAnnotation(const ParallelAnnotation*) = 0;
virtual std::string visitTrapAnnotation(const TrapAnnotation*) = 0;
virtual std::string visitExceptionAnnotation(const ExceptionAnnotation*) = 0;
virtual std::string visitPanicAnnotation(const PanicAnnotation*) = 0;
// Subject 4: Scope
virtual std::string visitBindingAnnotation(const BindingAnnotation*) = 0;
virtual std::string visitLookupAnnotation(const LookupAnnotation*) = 0;
virtual std::string visitCaptureAnnotation(const CaptureAnnotation*) = 0;
virtual std::string visitVisibilityAnnotation(const VisibilityAnnotation*) = 0;
virtual std::string visitNamespaceAnnotation(const NamespaceAnnotation*) = 0;
virtual std::string visitScopeAnnotation(const ScopeAnnotation*) = 0;
// Subject 5: Shims & Platform
virtual std::string visitIntrinsicAnnotation(const IntrinsicAnnotation*) = 0;
virtual std::string visitRawAnnotation(const RawAnnotation*) = 0;
virtual std::string visitCallingConvAnnotation(const CallingConvAnnotation*) = 0;
virtual std::string visitLinkAnnotation(const LinkAnnotation*) = 0;
virtual std::string visitShimAnnotation(const ShimAnnotation*) = 0;
virtual std::string visitPointerArithmeticAnnotation(const PointerArithmeticAnnotation*) = 0;
virtual std::string visitOpaqueAnnotation(const OpaqueAnnotation*) = 0;
virtual std::string visitTargetAnnotation(const TargetAnnotation*) = 0;
virtual std::string visitFeatureAnnotation(const FeatureAnnotation*) = 0;
virtual std::string visitOriginalAnnotation(const OriginalAnnotation*) = 0;
virtual std::string visitMappingAnnotation(const MappingAnnotation*) = 0;
// Subject 6: Optimization
virtual std::string visitTailCallAnnotation(const TailCallAnnotation*) = 0;
virtual std::string visitLoopAnnotation(const LoopAnnotation*) = 0;
virtual std::string visitDataAnnotation(const DataAnnotation*) = 0;
virtual std::string visitAlignAnnotation(const AlignAnnotation*) = 0;
virtual std::string visitPackAnnotation(const PackAnnotation*) = 0;
virtual std::string visitBoundsCheckAnnotation(const BoundsCheckAnnotation*) = 0;
virtual std::string visitOverflowAnnotation(const OverflowAnnotation*) = 0;
// Subject 7: Meta-Programming
virtual std::string visitMetaAnnotation(const MetaAnnotation*) = 0;
virtual std::string visitSymbolAnnotation(const SymbolAnnotation*) = 0;
virtual std::string visitEvaluateAnnotation(const EvaluateAnnotation*) = 0;
virtual std::string visitTemplateAnnotation(const TemplateAnnotation*) = 0;
virtual std::string visitSyntheticAnnotation(const SyntheticAnnotation*) = 0;
// Subject 8: Policy
virtual std::string visitPolicyAnnotation(const PolicyAnnotation*) = 0;
virtual std::string visitAmbiguityAnnotation(const AmbiguityAnnotation*) = 0;
virtual std::string visitCandidateAnnotation(const CandidateAnnotation*) = 0;
virtual std::string visitTradeoffAnnotation(const TradeoffAnnotation*) = 0;
virtual std::string visitChoiceAnnotation(const ChoiceAnnotation*) = 0;
virtual std::string visitDecisionAnnotation(const DecisionAnnotation*) = 0;
// Semantic Core
virtual std::string visitIntentAnnotation(const IntentAnnotation*) = 0;
virtual std::string visitComplexityAnnotation(const ComplexityAnnotation*) = 0;
virtual std::string visitRiskAnnotation(const RiskAnnotation*) = 0;
virtual std::string visitContractAnnotation(const ContractAnnotation*) = 0;
virtual std::string visitSemanticTagAnnotation(const SemanticTagAnnotation*) = 0;
// Environment
virtual std::string visitCapabilityRequirement(const CapabilityRequirement*) = 0;
};

View File

@@ -1,9 +1,12 @@
#pragma once
#include "ProjectionGenerator.h"
#include "../TypeAwareMappings.h"
#include "../SemannoAnnotationImpl.h"
class CppGenerator : public ProjectionGenerator {
class CppGenerator : public ProjectionGenerator, public SemannoAnnotationImpl<CppGenerator> {
public:
std::string commentPrefix() const { return "// "; }
std::string generate(const ASTNode* node) override {
return dispatchGenerate(this, node, "// Unknown concept: ");
}

View File

@@ -1,8 +1,11 @@
#pragma once
#include "ProjectionGenerator.h"
#include "../SemannoAnnotationImpl.h"
class ElispGenerator : public ProjectionGenerator {
class ElispGenerator : public ProjectionGenerator, public SemannoAnnotationImpl<ElispGenerator> {
public:
std::string commentPrefix() const { return ";; "; }
std::string generate(const ASTNode* node) override {
return dispatchGenerate(this, node, "; Unknown concept: ");
}

View File

@@ -9,3 +9,5 @@
#include "JavaGenerator.h"
#include "RustGenerator.h"
#include "GoGenerator.h"
#include "KotlinGenerator.h"
#include "CSharpGenerator.h"

View File

@@ -1,9 +1,12 @@
#pragma once
#include "ProjectionGenerator.h"
#include "Import.h"
#include "../SemannoAnnotationImpl.h"
class GoGenerator : public ProjectionGenerator {
class GoGenerator : public ProjectionGenerator, public SemannoAnnotationImpl<GoGenerator> {
public:
std::string commentPrefix() const { return "// "; }
std::string generate(const ASTNode* node) override {
return dispatchGenerate(this, node, "// Unknown concept: ");
}

View File

@@ -1,11 +1,14 @@
#pragma once
#include "ProjectionGenerator.h"
#include "Import.h"
#include "../SemannoAnnotationImpl.h"
#include <map>
#include <unordered_map>
class JavaGenerator : public ProjectionGenerator {
class JavaGenerator : public ProjectionGenerator, public SemannoAnnotationImpl<JavaGenerator> {
public:
std::string commentPrefix() const { return "// "; }
std::string generate(const ASTNode* node) override {
return dispatchGenerate(this, node, "// Unknown concept: ");
}

View File

@@ -1,11 +1,14 @@
#pragma once
#include "ProjectionGenerator.h"
#include "Import.h"
#include "../SemannoAnnotationImpl.h"
#include <unordered_map>
#include <unordered_set>
class JavaScriptGenerator : public ProjectionGenerator {
class JavaScriptGenerator : public ProjectionGenerator, public SemannoAnnotationImpl<JavaScriptGenerator> {
public:
std::string commentPrefix() const { return "// "; }
explicit JavaScriptGenerator(bool includeTypes = false)
: includeTypes_(includeTypes) {}

View File

@@ -153,5 +153,7 @@ public:
#include "ast/JavaParser.h"
#include "ast/RustParser.h"
#include "ast/GoParser.h"
#include "ast/KotlinParser.h"
#include "ast/CSharpParser.h"
private:
};

View File

@@ -12,8 +12,10 @@
#include "Expression.h"
#include "Type.h"
#include "Annotation.h"
#include "AnnotationVisitors.h"
#include "HostBoundary.h"
class ProjectionGenerator {
class ProjectionGenerator : public virtual AnnotationVisitorExtended {
public:
virtual ~ProjectionGenerator() = default;
@@ -61,6 +63,22 @@ public:
virtual std::string visitInlineAnnotation(const InlineAnnotation* annotation) = 0;
virtual std::string visitPureAnnotation(const PureAnnotation* annotation) = 0;
virtual std::string visitConstExprAnnotation(const ConstExprAnnotation* annotation) = 0;
// New AST node visitors (Phase 11c)
virtual std::string visitClassDeclaration(const ASTNode* node) { return ""; }
virtual std::string visitInterfaceDeclaration(const ASTNode* node) { return ""; }
virtual std::string visitMethodDeclaration(const ASTNode* node) { return ""; }
virtual std::string visitGenericType(const ASTNode* node) { return ""; }
virtual std::string visitTypeParameter(const ASTNode* node) { return ""; }
virtual std::string visitAsyncFunction(const ASTNode* node) { return ""; }
virtual std::string visitAwaitExpression(const ASTNode* node) { return ""; }
virtual std::string visitLambdaExpression(const ASTNode* node) { return ""; }
virtual std::string visitDecoratorAnnotation(const ASTNode* node) { return ""; }
// Host boundary visitors
virtual std::string visitHostCall(const HostCall* node) { return ""; }
virtual std::string visitScheduleTask(const ScheduleTask* node) { return ""; }
virtual std::string visitModuleLoad(const ModuleLoad* node) { return ""; }
};
// Shared dispatch: maps conceptType string to the appropriate visit call.
@@ -156,6 +174,170 @@ std::string dispatchGenerate(Gen* gen, const ASTNode* node, const std::string& u
} else if (node->conceptType == "ConstExprAnnotation") {
return gen->visitConstExprAnnotation(static_cast<const ConstExprAnnotation*>(node));
}
// Subject 2: Type System (Steps 291-292)
else if (node->conceptType == "BitWidthAnnotation") {
return gen->visitBitWidthAnnotation(static_cast<const BitWidthAnnotation*>(node));
} else if (node->conceptType == "EndianAnnotation") {
return gen->visitEndianAnnotation(static_cast<const EndianAnnotation*>(node));
} else if (node->conceptType == "LayoutAnnotation") {
return gen->visitLayoutAnnotation(static_cast<const LayoutAnnotation*>(node));
} else if (node->conceptType == "NullabilityAnnotation") {
return gen->visitNullabilityAnnotation(static_cast<const NullabilityAnnotation*>(node));
} else if (node->conceptType == "VarianceAnnotation") {
return gen->visitVarianceAnnotation(static_cast<const VarianceAnnotation*>(node));
} else if (node->conceptType == "IdentityAnnotation") {
return gen->visitIdentityAnnotation(static_cast<const IdentityAnnotation*>(node));
} else if (node->conceptType == "MutAnnotation") {
return gen->visitMutAnnotation(static_cast<const MutAnnotation*>(node));
} else if (node->conceptType == "TypeStateAnnotation") {
return gen->visitTypeStateAnnotation(static_cast<const TypeStateAnnotation*>(node));
}
// Subject 3: Concurrency
else if (node->conceptType == "AtomicAnnotation") {
return gen->visitAtomicAnnotation(static_cast<const AtomicAnnotation*>(node));
} else if (node->conceptType == "SyncAnnotation") {
return gen->visitSyncAnnotation(static_cast<const SyncAnnotation*>(node));
} else if (node->conceptType == "ThreadModelAnnotation") {
return gen->visitThreadModelAnnotation(static_cast<const ThreadModelAnnotation*>(node));
} else if (node->conceptType == "MemoryBarrierAnnotation") {
return gen->visitMemoryBarrierAnnotation(static_cast<const MemoryBarrierAnnotation*>(node));
} else if (node->conceptType == "ExecAnnotation") {
return gen->visitExecAnnotation(static_cast<const ExecAnnotation*>(node));
} else if (node->conceptType == "BlockingAnnotation") {
return gen->visitBlockingAnnotation(static_cast<const BlockingAnnotation*>(node));
} else if (node->conceptType == "ParallelAnnotation") {
return gen->visitParallelAnnotation(static_cast<const ParallelAnnotation*>(node));
} else if (node->conceptType == "TrapAnnotation") {
return gen->visitTrapAnnotation(static_cast<const TrapAnnotation*>(node));
} else if (node->conceptType == "ExceptionAnnotation") {
return gen->visitExceptionAnnotation(static_cast<const ExceptionAnnotation*>(node));
} else if (node->conceptType == "PanicAnnotation") {
return gen->visitPanicAnnotation(static_cast<const PanicAnnotation*>(node));
}
// Subject 4: Scope
else if (node->conceptType == "BindingAnnotation") {
return gen->visitBindingAnnotation(static_cast<const BindingAnnotation*>(node));
} else if (node->conceptType == "LookupAnnotation") {
return gen->visitLookupAnnotation(static_cast<const LookupAnnotation*>(node));
} else if (node->conceptType == "CaptureAnnotation") {
return gen->visitCaptureAnnotation(static_cast<const CaptureAnnotation*>(node));
} else if (node->conceptType == "VisibilityAnnotation") {
return gen->visitVisibilityAnnotation(static_cast<const VisibilityAnnotation*>(node));
} else if (node->conceptType == "NamespaceAnnotation") {
return gen->visitNamespaceAnnotation(static_cast<const NamespaceAnnotation*>(node));
} else if (node->conceptType == "ScopeAnnotation") {
return gen->visitScopeAnnotation(static_cast<const ScopeAnnotation*>(node));
}
// Subject 5: Shims & Platform
else if (node->conceptType == "IntrinsicAnnotation") {
return gen->visitIntrinsicAnnotation(static_cast<const IntrinsicAnnotation*>(node));
} else if (node->conceptType == "RawAnnotation") {
return gen->visitRawAnnotation(static_cast<const RawAnnotation*>(node));
} else if (node->conceptType == "CallingConvAnnotation") {
return gen->visitCallingConvAnnotation(static_cast<const CallingConvAnnotation*>(node));
} else if (node->conceptType == "LinkAnnotation") {
return gen->visitLinkAnnotation(static_cast<const LinkAnnotation*>(node));
} else if (node->conceptType == "ShimAnnotation") {
return gen->visitShimAnnotation(static_cast<const ShimAnnotation*>(node));
} else if (node->conceptType == "PointerArithmeticAnnotation") {
return gen->visitPointerArithmeticAnnotation(static_cast<const PointerArithmeticAnnotation*>(node));
} else if (node->conceptType == "OpaqueAnnotation") {
return gen->visitOpaqueAnnotation(static_cast<const OpaqueAnnotation*>(node));
} else if (node->conceptType == "TargetAnnotation") {
return gen->visitTargetAnnotation(static_cast<const TargetAnnotation*>(node));
} else if (node->conceptType == "FeatureAnnotation") {
return gen->visitFeatureAnnotation(static_cast<const FeatureAnnotation*>(node));
} else if (node->conceptType == "OriginalAnnotation") {
return gen->visitOriginalAnnotation(static_cast<const OriginalAnnotation*>(node));
} else if (node->conceptType == "MappingAnnotation") {
return gen->visitMappingAnnotation(static_cast<const MappingAnnotation*>(node));
}
// Subject 6: Optimization
else if (node->conceptType == "TailCallAnnotation") {
return gen->visitTailCallAnnotation(static_cast<const TailCallAnnotation*>(node));
} else if (node->conceptType == "LoopAnnotation") {
return gen->visitLoopAnnotation(static_cast<const LoopAnnotation*>(node));
} else if (node->conceptType == "DataAnnotation") {
return gen->visitDataAnnotation(static_cast<const DataAnnotation*>(node));
} else if (node->conceptType == "AlignAnnotation") {
return gen->visitAlignAnnotation(static_cast<const AlignAnnotation*>(node));
} else if (node->conceptType == "PackAnnotation") {
return gen->visitPackAnnotation(static_cast<const PackAnnotation*>(node));
} else if (node->conceptType == "BoundsCheckAnnotation") {
return gen->visitBoundsCheckAnnotation(static_cast<const BoundsCheckAnnotation*>(node));
} else if (node->conceptType == "OverflowAnnotation") {
return gen->visitOverflowAnnotation(static_cast<const OverflowAnnotation*>(node));
}
// Subject 7: Meta-Programming
else if (node->conceptType == "MetaAnnotation") {
return gen->visitMetaAnnotation(static_cast<const MetaAnnotation*>(node));
} else if (node->conceptType == "SymbolAnnotation") {
return gen->visitSymbolAnnotation(static_cast<const SymbolAnnotation*>(node));
} else if (node->conceptType == "EvaluateAnnotation") {
return gen->visitEvaluateAnnotation(static_cast<const EvaluateAnnotation*>(node));
} else if (node->conceptType == "TemplateAnnotation") {
return gen->visitTemplateAnnotation(static_cast<const TemplateAnnotation*>(node));
} else if (node->conceptType == "SyntheticAnnotation") {
return gen->visitSyntheticAnnotation(static_cast<const SyntheticAnnotation*>(node));
}
// Subject 8: Policy
else if (node->conceptType == "PolicyAnnotation") {
return gen->visitPolicyAnnotation(static_cast<const PolicyAnnotation*>(node));
} else if (node->conceptType == "AmbiguityAnnotation") {
return gen->visitAmbiguityAnnotation(static_cast<const AmbiguityAnnotation*>(node));
} else if (node->conceptType == "CandidateAnnotation") {
return gen->visitCandidateAnnotation(static_cast<const CandidateAnnotation*>(node));
} else if (node->conceptType == "TradeoffAnnotation") {
return gen->visitTradeoffAnnotation(static_cast<const TradeoffAnnotation*>(node));
} else if (node->conceptType == "ChoiceAnnotation") {
return gen->visitChoiceAnnotation(static_cast<const ChoiceAnnotation*>(node));
} else if (node->conceptType == "DecisionAnnotation") {
return gen->visitDecisionAnnotation(static_cast<const DecisionAnnotation*>(node));
}
// Semantic Core
else if (node->conceptType == "IntentAnnotation") {
return gen->visitIntentAnnotation(static_cast<const IntentAnnotation*>(node));
} else if (node->conceptType == "ComplexityAnnotation") {
return gen->visitComplexityAnnotation(static_cast<const ComplexityAnnotation*>(node));
} else if (node->conceptType == "RiskAnnotation") {
return gen->visitRiskAnnotation(static_cast<const RiskAnnotation*>(node));
} else if (node->conceptType == "ContractAnnotation") {
return gen->visitContractAnnotation(static_cast<const ContractAnnotation*>(node));
} else if (node->conceptType == "SemanticTagAnnotation") {
return gen->visitSemanticTagAnnotation(static_cast<const SemanticTagAnnotation*>(node));
}
// Environment
else if (node->conceptType == "CapabilityRequirement") {
return gen->visitCapabilityRequirement(static_cast<const CapabilityRequirement*>(node));
}
// Host Boundary (Step 288)
else if (node->conceptType == "HostCall") {
return gen->visitHostCall(static_cast<const HostCall*>(node));
} else if (node->conceptType == "ScheduleTask") {
return gen->visitScheduleTask(static_cast<const ScheduleTask*>(node));
} else if (node->conceptType == "ModuleLoad") {
return gen->visitModuleLoad(static_cast<const ModuleLoad*>(node));
}
// New AST nodes (Phase 11c)
else if (node->conceptType == "ClassDeclaration") {
return gen->visitClassDeclaration(node);
} else if (node->conceptType == "InterfaceDeclaration") {
return gen->visitInterfaceDeclaration(node);
} else if (node->conceptType == "MethodDeclaration") {
return gen->visitMethodDeclaration(node);
} else if (node->conceptType == "GenericType") {
return gen->visitGenericType(node);
} else if (node->conceptType == "TypeParameter") {
return gen->visitTypeParameter(node);
} else if (node->conceptType == "AsyncFunction") {
return gen->visitAsyncFunction(node);
} else if (node->conceptType == "AwaitExpression") {
return gen->visitAwaitExpression(node);
} else if (node->conceptType == "LambdaExpression") {
return gen->visitLambdaExpression(node);
} else if (node->conceptType == "DecoratorAnnotation") {
return gen->visitDecoratorAnnotation(node);
}
return unknownPrefix + node->conceptType;
}

View File

@@ -1,9 +1,12 @@
#pragma once
#include "ProjectionGenerator.h"
#include "../SemannoAnnotationImpl.h"
class PythonGenerator : public ProjectionGenerator {
class PythonGenerator : public ProjectionGenerator, public SemannoAnnotationImpl<PythonGenerator> {
public:
std::string commentPrefix() const { return "# "; }
std::string generate(const ASTNode* node) override {
return dispatchGenerate(this, node, "# Unknown concept: ");
}

View File

@@ -1,9 +1,12 @@
#pragma once
#include "ProjectionGenerator.h"
#include "Import.h"
#include "../SemannoAnnotationImpl.h"
class RustGenerator : public ProjectionGenerator {
class RustGenerator : public ProjectionGenerator, public SemannoAnnotationImpl<RustGenerator> {
public:
std::string commentPrefix() const { return "// "; }
std::string generate(const ASTNode* node) override {
return dispatchGenerate(this, node, "// Unknown concept: ");
}

View File

@@ -14,6 +14,9 @@
#include "Import.h"
#include "ExternalModule.h"
#include "TypeSignature.h"
#include "ClassDeclaration.h"
#include "GenericType.h"
#include "AsyncNodes.h"
using json = nlohmann::json;
@@ -418,6 +421,49 @@ inline json propertiesToJson(const ASTNode* node) {
if (!n->capability.empty()) props["capability"] = n->capability;
props["required"] = n->required;
}
// New AST nodes (Sprint 11c)
else if (ct == "ClassDeclaration") {
auto* n = static_cast<const ClassDeclaration*>(node);
props["name"] = n->name;
if (!n->superClass.empty()) props["superClass"] = n->superClass;
props["isAbstract"] = n->isAbstract;
}
else if (ct == "InterfaceDeclaration") {
auto* n = static_cast<const InterfaceDeclaration*>(node);
props["name"] = n->name;
}
else if (ct == "MethodDeclaration") {
auto* n = static_cast<const MethodDeclaration*>(node);
props["name"] = n->name;
if (!n->className.empty()) props["className"] = n->className;
props["isStatic"] = n->isStatic;
if (!n->visibility.empty()) props["visibility"] = n->visibility;
props["isOverride"] = n->isOverride;
props["isVirtual"] = n->isVirtual;
}
else if (ct == "GenericType") {
auto* n = static_cast<const GenericType*>(node);
props["baseName"] = n->baseName;
}
else if (ct == "TypeParameter") {
auto* n = static_cast<const TypeParameter*>(node);
props["name"] = n->name;
if (!n->constraint.empty()) props["constraint"] = n->constraint;
}
else if (ct == "AsyncFunction") {
auto* n = static_cast<const AsyncFunction*>(node);
props["name"] = n->name;
props["isAsync"] = n->isAsync;
}
// AwaitExpression — no extra properties
else if (ct == "LambdaExpression") {
auto* n = static_cast<const LambdaExpression*>(node);
if (!n->captureList.empty()) props["captureList"] = n->captureList;
}
else if (ct == "DecoratorAnnotation") {
auto* n = static_cast<const DecoratorAnnotation*>(node);
props["name"] = n->name;
}
// NullLiteral, ListLiteral, IndexAccess, Block, Assignment, IfStatement,
// WhileLoop, Return, ExpressionStatement, ListType, SetType, MapType,
// TupleType, ArrayType, OptionalType — no extra properties
@@ -565,6 +611,16 @@ inline ASTNode* createNode(const std::string& conceptName) {
// Environment Layer (Step 284-285)
if (conceptName == "EnvironmentSpec") return new EnvironmentSpec();
if (conceptName == "CapabilityRequirement") return new CapabilityRequirement();
// New AST nodes (Sprint 11c)
if (conceptName == "ClassDeclaration") return new ClassDeclaration();
if (conceptName == "InterfaceDeclaration") return new InterfaceDeclaration();
if (conceptName == "MethodDeclaration") return new MethodDeclaration();
if (conceptName == "GenericType") return new GenericType();
if (conceptName == "TypeParameter") return new TypeParameter();
if (conceptName == "AsyncFunction") return new AsyncFunction();
if (conceptName == "AwaitExpression") return new AwaitExpression();
if (conceptName == "LambdaExpression") return new LambdaExpression();
if (conceptName == "DecoratorAnnotation") return new DecoratorAnnotation();
return nullptr;
}
@@ -990,6 +1046,53 @@ inline void setPropertiesFromJson(ASTNode* node, const json& props) {
if (props.contains("capability")) n->capability = props["capability"].get<std::string>();
if (props.contains("required")) n->required = props["required"].get<bool>();
}
// New AST nodes (Sprint 11c)
else if (ct == "ClassDeclaration") {
auto* n = static_cast<ClassDeclaration*>(node);
if (props.contains("name")) n->name = props["name"].get<std::string>();
if (props.contains("superClass")) n->superClass = props["superClass"].get<std::string>();
if (props.contains("isAbstract")) n->isAbstract = props["isAbstract"].get<bool>();
}
else if (ct == "InterfaceDeclaration") {
auto* n = static_cast<InterfaceDeclaration*>(node);
if (props.contains("name")) n->name = props["name"].get<std::string>();
}
else if (ct == "MethodDeclaration") {
auto* n = static_cast<MethodDeclaration*>(node);
if (props.contains("name")) n->name = props["name"].get<std::string>();
if (props.contains("className")) n->className = props["className"].get<std::string>();
if (props.contains("isStatic")) n->isStatic = props["isStatic"].get<bool>();
if (props.contains("visibility")) n->visibility = props["visibility"].get<std::string>();
if (props.contains("isOverride")) n->isOverride = props["isOverride"].get<bool>();
if (props.contains("isVirtual")) n->isVirtual = props["isVirtual"].get<bool>();
}
else if (ct == "GenericType") {
auto* n = static_cast<GenericType*>(node);
if (props.contains("baseName")) n->baseName = props["baseName"].get<std::string>();
}
else if (ct == "TypeParameter") {
auto* n = static_cast<TypeParameter*>(node);
if (props.contains("name")) n->name = props["name"].get<std::string>();
if (props.contains("constraint")) n->constraint = props["constraint"].get<std::string>();
}
else if (ct == "AsyncFunction") {
auto* n = static_cast<AsyncFunction*>(node);
if (props.contains("name")) n->name = props["name"].get<std::string>();
if (props.contains("isAsync")) n->isAsync = props["isAsync"].get<bool>();
}
// AwaitExpression — no extra properties
else if (ct == "LambdaExpression") {
auto* n = static_cast<LambdaExpression*>(node);
if (props.contains("captureList") && props["captureList"].is_array()) {
n->captureList.clear();
for (const auto& c : props["captureList"])
if (c.is_string()) n->captureList.push_back(c.get<std::string>());
}
}
else if (ct == "DecoratorAnnotation") {
auto* n = static_cast<DecoratorAnnotation*>(node);
if (props.contains("name")) n->name = props["name"].get<std::string>();
}
}
inline std::string generateNodeId() {