R/core.R

Defines functions fingerprint deserialize validate_record .decode_expr serialize .plain ordinal_term .natural validate_context .result .facts add_assumption .check_context theory_context parse_formula normalize relativize substitute free_variables .walk exists forall equivalence implication disjunction conjunction negate member equal predicate constant variable .expr .fields .array .scalar_string .name .require .lc_stop

Documented in add_assumption conjunction constant deserialize disjunction equal equivalence fingerprint forall free_variables implication member negate normalize ordinal_term parse_formula predicate relativize theory_context validate_context validate_record variable

# Native symbolic syntax and explicitly scoped theory contexts.
.lc_stop <- function(message, code = "INVALID_INPUT", ...) {
  stop(structure(list(message = message, call = NULL, code = code, details = list(...)),
                 class = c("largecardinals_error", "error", "condition")))
}
.require <- function(value, message, code = "INVALID_INPUT") {
  if (length(value) != 1L || is.na(value) || !isTRUE(value)) .lc_stop(message, code)
}
.name <- function(x) {
  .require(is.character(x) && length(x) == 1L && !is.na(x) &&
             grepl("^[A-Za-z_][A-Za-z_0-9.]*$", x), "Expected an ASCII mathematical identifier")
  x
}
.scalar_string <- function(x) is.character(x) && length(x) == 1L && !is.na(x)
.array <- function(x) unname(as.list(x))
.fields <- function(x, expected) is.list(x) && setequal(names(x), expected) && !anyDuplicated(names(x))
.expr <- function(op, args = list(), name = NULL, sort = "formula") {
  .require(.scalar_string(op) && op %in% c("var", "const", "pred", "eq", "in", "not", "and", "or", "implies", "iff", "forall", "exists"), "Invalid AST operation")
  .require(is.list(args) && all(vapply(args, inherits, logical(1), "lc_expression")), "AST arguments must be expressions")
  if (op %in% c("var", "const")) {
    .name(name)
    .require(sort %in% c("set", "ordinal", "cardinal", "class", "real", "natural") && !length(args), "Invalid term")
  } else {
    .require(identical(sort, "formula"), "Connectives must have formula sort")
    if (op == "pred") {
      .name(name)
      .require(all(vapply(args, function(a) a$sort != "formula", logical(1))), "Predicate arguments must be terms")
    } else {
      .require(is.null(name), "Unexpected connective name")
      if (op %in% c("forall", "exists")) {
        .require(length(args) == 2L && args[[1L]]$op == "var" && args[[2L]]$sort == "formula", "Quantifier needs a variable and formula")
        bound <- args[[1L]]; pending <- list(args[[2L]])
        while(length(pending)) {
          node <- pending[[length(pending)]]; pending <- pending[-length(pending)]
          if(node$op=="var" && node$name==bound$name) .require(node$sort==bound$sort,"Bound variable sort mismatch")
          else if(node$op %in% c("forall","exists") && node$args[[1L]]$name==bound$name) next
          else pending <- c(pending,node$args)
        }
      } else if (op %in% c("eq", "in")) {
        .require(length(args) == 2L && all(vapply(args, function(a) a$sort != "formula", logical(1))), "Binary relation needs two terms")
        if (op == "in") .require(args[[1L]]$sort != "class", "A proper class cannot be a member")
      } else {
        arity <- switch(op, not = 1L, implies = 2L, iff = 2L, NULL)
        .require(is.null(arity) || length(args) == arity, "Invalid connective arity")
        .require(all(vapply(args, function(a) a$sort == "formula", logical(1))), "Expected formula arguments")
      }
    }
  }
  structure(list(type = "expression", op = op, args = unname(args), name = name, sort = sort), class = c("lc_expression", "list"))
}
variable <- function(name, sort = "set") .expr("var", name = name, sort = sort)
constant <- function(name, sort = "set") .expr("const", name = name, sort = sort)
predicate <- function(name, ...) .expr("pred", list(...), name = name)
equal <- function(left, right) .expr("eq", list(left, right))
member <- function(left, right) .expr("in", list(left, right))
negate <- function(body) .expr("not", list(body))
conjunction <- function(...) .expr("and", list(...))
disjunction <- function(...) .expr("or", list(...))
implication <- function(left, right) .expr("implies", list(left, right))
equivalence <- function(left, right) .expr("iff", list(left, right))
forall <- function(bound, body) .expr("forall", list(bound, body))
exists <- function(bound, body) .expr("exists", list(bound, body))
.walk <- function(expr, limit = 10000L) {
  .require(inherits(expr, "lc_expression"), "Expected an expression")
  out <- list(); stack <- list(list(node = expr, depth = 0L))
  while (length(stack)) {
    item <- stack[[length(stack)]]; stack <- stack[-length(stack)]
    .require(length(out) < limit && item$depth <= 128L, "Expression size/depth limit exceeded", "RESOURCE_LIMIT")
    out[[length(out) + 1L]] <- item$node
    for (child in rev(item$node$args)) stack[[length(stack) + 1L]] <- list(node = child, depth = item$depth + 1L)
  }
  out
}
free_variables <- function(expr) {
  .walk(expr)
  rec <- function(e, bound) {
    if (e$op == "var") return(if (e$name %in% bound) character() else e$name)
    if (e$op %in% c("forall", "exists")) return(rec(e$args[[2L]], union(bound, e$args[[1L]]$name)))
    unique(unlist(lapply(e$args, rec, bound = bound), use.names = FALSE))
  }
  sort(as.character(rec(expr, character())), method = "radix")
}
substitute <- function(expr, name, replacement) {
  .name(name)
  .require(inherits(replacement, "lc_expression") && replacement$sort != "formula", "Substitution requires a term")
  nodes <- c(.walk(expr), .walk(replacement)); used <- unique(unlist(lapply(nodes, `[[`, "name")))
  free <- free_variables(replacement)
  fresh <- function() {
    i <- 0L
    while (paste0("_fresh", i) %in% used) i <- i + 1L
    value <- paste0("_fresh", i); used <<- c(used, value); value
  }
  rename <- function(e, old, new) {
    if (e$op == "var" && e$name == old) return(variable(new, e$sort))
    if (e$op %in% c("forall", "exists") && e$args[[1L]]$name == old) return(e)
    .expr(e$op, lapply(e$args, rename, old = old, new = new), e$name, e$sort)
  }
  rec <- function(e) {
    if (e$op == "var" && e$name == name) {
      .require(e$sort == replacement$sort, "Substitution sort mismatch"); return(replacement)
    }
    if (e$op %in% c("forall", "exists")) {
      bound <- e$args[[1L]]; body <- e$args[[2L]]
      if (bound$name == name) return(e)
      if (bound$name %in% free && name %in% free_variables(body)) {
        new <- fresh(); body <- rename(body, bound$name, new); bound <- variable(new, bound$sort)
      }
      return(.expr(e$op, list(bound, rec(body))))
    }
    .expr(e$op, lapply(e$args, rec), e$name, e$sort)
  }
  rec(expr)
}
relativize <- function(expr, domain) {
  .require(inherits(expr,"lc_expression") && expr$sort=="formula","Expected a formula")
  .require(inherits(domain,"lc_expression") && domain$sort %in% c("set","class"),"Domain must be a set or class term")
  nodes <- c(.walk(expr),.walk(domain))
  used <- unique(unlist(lapply(nodes,`[[`,"name"),use.names=FALSE))
  for(node in nodes) if(node$op %in% c("forall","exists"))
    .require(node$args[[1L]]$sort=="set","Relativization supports only set-sorted binders","UNSUPPORTED")
  rec <- function(e) {
    if(e$op %in% c("forall","exists")) {
      bound <- e$args[[1L]]; body <- e$args[[2L]]
      if(domain$op=="var" && bound$name==domain$name) {
        index <- 0L
        while(paste0("_rel",index) %in% used) index <- index+1L
        name <- paste0("_rel",index); used <<- c(used,name)
        renamed <- variable(name,bound$sort)
        body <- substitute(body,bound$name,renamed); bound <- renamed
      }
      guard <- member(bound,domain)
      restricted <- if(e$op=="forall") implication(guard,rec(body)) else conjunction(guard,rec(body))
      return(.expr(e$op,list(bound,restricted)))
    }
    .expr(e$op,lapply(e$args,rec),e$name,e$sort)
  }
  result <- rec(expr); .walk(result); result
}
normalize <- function(expr) {
  .walk(expr); free <- free_variables(expr); counter <- 0L
  rec <- function(e, env) {
    if (e$op == "var") return(variable(if (e$name %in% names(env)) env[[e$name]] else e$name, e$sort))
    if (e$op %in% c("forall", "exists")) {
      while (paste0("_bound", counter) %in% free) counter <<- counter + 1L
      new <- paste0("_bound", counter); counter <<- counter + 1L
      bound <- e$args[[1L]]; env[[bound$name]] <- new
      return(.expr(e$op, list(variable(new, bound$sort), rec(e$args[[2L]], env))))
    }
    .expr(e$op, lapply(e$args, rec, env = env), e$name, e$sort)
  }
  rec(expr, list())
}
parse_formula <- function(source, max_tokens = 10000L) {
  .require(.scalar_string(source) && nchar(source, type = "bytes") <= 1000000L, "Invalid/oversized formula text")
  .require(is.numeric(max_tokens) && length(max_tokens)==1L && is.finite(max_tokens) && max_tokens==floor(max_tokens) && max_tokens>=1L && max_tokens<=1000000L,"Token budget must be an integer between 1 and 1000000")
  tokens <- regmatches(source, gregexpr("\\(|\\)|[^\\s()]+", source, perl = TRUE))[[1L]]
  .require(length(tokens) <= max_tokens, "Token limit exceeded", "RESOURCE_LIMIT")
  pos <- 1L
  term <- function(x) if (startsWith(x, "$")) constant(substring(x, 2L)) else variable(x)
  rec <- function(depth = 0L) {
    .require(depth <= 100L, "Parser depth exceeded", "RESOURCE_LIMIT")
    .require(pos <= length(tokens), "Unexpected end of formula")
    tok <- tokens[[pos]]; pos <<- pos + 1L
    if (tok != "(") { .require(tok != ")", "Unexpected closing delimiter"); return(predicate(tok)) }
    .require(pos <= length(tokens), "Missing operation")
    op <- tokens[[pos]]; pos <<- pos + 1L
    if (op %in% c("forall", "exists")) {
      .require(pos <= length(tokens), "Missing binder")
      bound <- variable(tokens[[pos]]); pos <<- pos + 1L
      out <- .expr(op, list(bound, rec(depth + 1L)))
    } else {
      args <- list()
      while (pos <= length(tokens) && tokens[[pos]] != ")") {
        if (op %in% c("not", "and", "or", "implies", "iff")) args[[length(args)+1L]] <- rec(depth+1L)
        else { args[[length(args)+1L]] <- term(tokens[[pos]]); pos <<- pos + 1L }
      }
      out <- if (op %in% c("not", "and", "or", "implies", "iff", "eq", "in")) .expr(op, args) else .expr("pred", args, op)
    }
    .require(pos <= length(tokens) && tokens[[pos]] == ")", "Missing closing delimiter")
    pos <<- pos + 1L; out
  }
  value <- rec(); .require(pos > length(tokens), "Trailing formula input"); value
}
theory_context <- function(base = "ZFC", assumptions = character(), model = "V", class_framework = "SCHEMA") {
  .require(.scalar_string(base) && base %in% c("ZF", "ZF_DC", "ZFC", "FOL"), "Unsupported base theory")
  .require(.scalar_string(class_framework) && class_framework %in% c("NONE", "SCHEMA", "NBG", "GB"), "Invalid class framework")
  .require(.scalar_string(model) && nzchar(model) && nchar(model) <= 200L, "Invalid model label")
  values <- unlist(assumptions, use.names = FALSE)
  .require(!length(values) || (is.character(values) && !anyNA(values) && all(nzchar(values))), "Assumptions must be nonempty strings")
  list(type = "theory_context", base = base, assumptions = .array(sort(unique(as.character(values)), method = "radix")),
       model = model, class_framework = class_framework, consistency_status = "NOT_ESTABLISHED")
}
.check_context <- function(context) {
  .require(is.list(context) && identical(context$type, "theory_context"), "Expected a theory context")
  expected <- theory_context(context$base, context$assumptions, context$model, context$class_framework)
  .require(identical(serialize(expected), serialize(context)), "Malformed or noncanonical theory context")
  context
}
add_assumption <- function(context, assumption) {
  .check_context(context)
  theory_context(context$base, c(context$assumptions, list(assumption)), context$model, context$class_framework)
}
.facts <- function(context) {
  .check_context(context); facts <- unlist(context$assumptions, use.names = FALSE)
  if (context$base %in% c("ZF", "ZF_DC", "ZFC")) facts <- c(facts, "ZF")
  if (context$base %in% c("ZF_DC", "ZFC")) facts <- c(facts, "DC")
  if (context$base == "ZFC" || "AC" %in% facts) facts <- c(facts, "AC", "DC")
  if ("ZF" %in% facts) {
    if ("AD_R" %in% facts) facts <- c(facts,"AD_mixed")
    if ("AD_mixed" %in% facts) facts <- c(facts,"AD")
    if ("AD" %in% facts) facts <- c(facts,"PD","AC_omega_reals")
    if ("DC" %in% facts) facts <- c(facts,"AC_omega_reals")
  }
  sort(unique(as.character(facts)), method = "radix")
}
.result <- function(status, mode, claim, context = NULL, assumptions = list(), evidence = list(), dependencies = list(), limitations = list(), witness = NULL, ...) {
  c(list(type = "query_result", status = status, mode = mode, claim = claim, context = context,
         assumptions = .array(assumptions), evidence = .array(evidence), dependencies = .array(dependencies),
         limitations = .array(limitations), witness = witness), list(...))
}
validate_context <- function(context) {
  facts <- .facts(context); pairs <- facts[paste0("not:", facts) %in% facts]
  if (all(c("AC", "AD") %in% facts)) pairs <- c(pairs, "AC with AD in the same model")
  .result(if (length(pairs)) "INCONSISTENT_CONTEXT" else "UNKNOWN", "SYMBOLIC", "context_consistency", context,
          assumptions = facts, witness = .array(pairs), limitations = c(
            "Named-axiom closure uses AC=>DC and, over ZF, AD_R=>AD_mixed=>AD=>PD, AD=>AC_omega_reals, DC=>AC_omega_reals.",
            "Only negation pairs in that closure and the same-model AC/AD conflict are checked.",
            "Absence of a detected contradiction does not establish consistency."))
}
.natural <- function(value) {
  if (is.numeric(value)) {
    .require(length(value)==1L && is.finite(value) && value >= 0 && value <= 2^53-1 && value == floor(value), "Use a decimal string for a large exact integer")
    value <- format(value, scientific = FALSE, trim = TRUE)
  }
  .require(.scalar_string(value) && grepl("^(0|[1-9][0-9]*)$", value), "Expected a nonnegative exact integer or canonical decimal string")
  .require(nchar(value) <= 1000L, "Integer digit limit exceeded", "RESOURCE_LIMIT"); value
}
ordinal_term <- function(kind, ...) {
  arities <- c(finite=1L, symbol=1L, omega=0L, successor=1L, sum=2L, product=2L, power=2L, aleph=1L, beth=1L)
  args <- list(...)
  .require(.scalar_string(kind) && kind %in% names(arities) && length(args)==arities[[kind]], "Invalid ordinal constructor/arity")
  if (kind == "finite") args <- list(.natural(args[[1L]]))
  else if (kind == "symbol") args <- list(.name(args[[1L]]))
  else .require(all(vapply(args, function(x) is.list(x) && identical(x$type,"ordinal_term"), logical(1))), "Ordinal operands must be ordinal terms")
  list(type="ordinal_term", kind=kind, args=unname(args))
}
.plain <- function(value, depth=0L) {
  .require(depth <= 128L, "Serialization depth exceeded", "RESOURCE_LIMIT")
  if (is.null(value)) return(NULL)
  if (is.list(value)) {
    .require(!is.data.frame(value), "Data frames are not interchange records")
    nms <- names(value)
    if (!is.null(nms)) {
      .require(!anyNA(nms) && !anyDuplicated(nms) && all(nzchar(nms)), "Duplicate/invalid JSON keys")
      value <- value[order(nms, method="radix")]
    }
    out <- lapply(value, .plain, depth=depth+1L)
    if (is.null(nms)) out <- unname(out)
    return(out)
  }
  .require(!anyNA(value), "NA is not null or UNKNOWN")
  if (length(value) != 1L) return(lapply(as.list(value), .plain, depth=depth+1L))
  if (is.character(value) || is.logical(value)) return(unname(value))
  if (is.numeric(value)) {
    .require(is.finite(value) && value==floor(value) && abs(value)<=2^53-1, "Only exact finite integers are serializable")
    return(unname(value))
  }
  .lc_stop("Unsupported interchange value")
}
serialize <- function(value) {
  as.character(jsonlite::toJSON(.plain(value), auto_unbox=TRUE, null="null", digits=NA, force=TRUE))
}
.decode_expr <- function(value) {
  .require(.fields(value,c("type","op","args","name","sort")) && identical(value$type,"expression") && is.list(value$args), "Invalid expression fields")
  .expr(value$op,lapply(value$args,.decode_expr),value$name,value$sort)
}
validate_record <- function(value) {
  value <- .plain(value)
  .require(is.list(value) && .scalar_string(value$type), "Expected a typed record")
  kind <- value$type
  if (kind == "expression") .walk(.decode_expr(value))
  else if (kind == "theory_context") .check_context(value)
  else if (kind == "ordinal_term") {
    .require(.fields(value,c("type","kind","args")), "Unexpected ordinal fields")
    .require(is.list(value$args) && is.null(names(value$args)),"Ordinal args must be an array")
    for (x in value$args) if(is.list(x)) validate_record(x)
    expected <- do.call(ordinal_term,c(list(kind=value$kind),value$args))
    .require(identical(serialize(value),serialize(expected)), "Invalid ordinal record")
  } else if (kind == "query_result") {
    .require(value$status %in% c("ESTABLISHED","REFUTED","UNKNOWN","INDEPENDENT","NOT_APPLICABLE","UNSUPPORTED","INCONSISTENT_CONTEXT"), "Invalid result status")
    .require(value$mode %in% c("SYMBOLIC","FINITE_EXACT","CATALOGUE","CHECKED_DERIVATION"), "Invalid result mode")
    .require(all(c("claim","context","assumptions","evidence","dependencies","limitations","witness") %in% names(value)), "Incomplete result")
    if(!is.null(value$context)) .check_context(value$context)
    for(key in c("assumptions","evidence","dependencies","limitations")) .require(is.list(value[[key]]) && is.null(names(value[[key]])),"Result metadata must use arrays")
    for(key in c("assumptions","dependencies","limitations")) .require(all(vapply(value[[key]],.scalar_string,logical(1))),"Expected textual result metadata")
  } else if(kind=="specification") validate_specification(value)
  else if(kind %in% c("finite_structure","finite_tree","finite_poset")) {
    if(kind=="finite_structure") {
      .require(.fields(value,c("type","domain","relations","constants")),"Invalid structure fields")
      expected <- finite_structure(value$domain,value$relations,value$constants)
    } else if(kind=="finite_tree") {
      .require(.fields(value,c("type","nodes")),"Invalid tree fields"); expected <- finite_tree(value$nodes)
    } else {
      .require(.fields(value,c("type","domain","order","convention")),"Invalid poset fields")
      expected <- finite_poset(value$domain,value$order)
    }
    .require(identical(serialize(value),serialize(expected)),"Noncanonical finite record")
  } else if(kind=="derivation") check_derivation(value)
  else if(kind=="relation_graph") .check_graph(value)
  else if(kind %in% c("definition","statement","catalogue_manifest")) {
    expected <- if(kind=="catalogue_manifest") catalogue_manifest() else if(kind=="definition") definition(value$id) else lookup_statement(value$id)
    .require(identical(serialize(value),serialize(expected)),"Record does not match the installed catalogue")
  } else .lc_stop("Unknown record type")
  value
}
deserialize <- function(text) {
  .require(.scalar_string(text), "JSON input must be text")
  .require(nchar(text,type="bytes")<=2000000L,"JSON input limit exceeded","RESOURCE_LIMIT")
  outside_strings <- gsub('"([^"\\\\]|\\\\.)*"', '""', text, perl=TRUE)
  .require(!grepl('-?[0-9]+([.][0-9]+|[eE][+-]?[0-9]+)',outside_strings,perl=TRUE),
           "JSON numbers must use integer notation; use decimal strings for large exact integers")
  value <- tryCatch(jsonlite::fromJSON(text,simplifyVector=FALSE),error=function(e) .lc_stop("Malformed JSON"))
  value <- validate_record(value)
  if (identical(value$type,"expression")) .decode_expr(value) else value
}
fingerprint <- function(value) digest::digest(serialize(value),algo="sha256",serialize=FALSE)

# Public names avoid masking base R functions used by package tooling.
exists_formula <- exists
substitute_formula <- substitute
serialize_record <- serialize

Try the largecardinals package in your browser

Any scripts or data that you put into this service are public.

largecardinals documentation built on Nov. 25, 2026, 5:09 p.m.