mirror of
https://github.com/roc-lang/roc.git
synced 2025-09-30 07:14:46 +00:00
Merge branch 'trunk' into inkwell-llvm-12-bump
This commit is contained in:
commit
87dbd044ea
67 changed files with 1466 additions and 538 deletions
1
.github/workflows/ci.yml
vendored
1
.github/workflows/ci.yml
vendored
|
@ -22,4 +22,3 @@ jobs:
|
|||
|
||||
- name: install dependencies, build, run zig tests, rustfmt, clippy, cargo test --release
|
||||
run: ./ci/safe-earthly.sh +test-all
|
||||
|
||||
|
|
22
.github/workflows/www.yml
vendored
Normal file
22
.github/workflows/www.yml
vendored
Normal file
|
@ -0,0 +1,22 @@
|
|||
name: deploy www.roc-lang.org
|
||||
|
||||
# Whenever a commit lands on trunk, deploy the site
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- deploy-www # TODO change to trunk
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: 'Deploy to Netlify'
|
||||
runs-on: [self-hosted]
|
||||
steps:
|
||||
- uses: jsmrcaga/action-netlify-deploy@v1.6.0
|
||||
with:
|
||||
install_command: 'pwd; cd ../../www'
|
||||
build_command: 'bash build.sh'
|
||||
build_directory: 'build'
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
|
||||
NETLIFY_DEPLOY_MESSAGE: "Deploy git ref ${{ github.ref }}"
|
||||
NETLIFY_DEPLOY_TO_PROD: true
|
76
Cargo.lock
generated
76
Cargo.lock
generated
|
@ -2943,7 +2943,7 @@ dependencies = [
|
|||
"roc_can",
|
||||
"roc_collections",
|
||||
"roc_constrain",
|
||||
"roc_gen",
|
||||
"roc_gen_llvm",
|
||||
"roc_load",
|
||||
"roc_module",
|
||||
"roc_mono",
|
||||
|
@ -3025,7 +3025,7 @@ dependencies = [
|
|||
"roc_docs",
|
||||
"roc_editor",
|
||||
"roc_fmt",
|
||||
"roc_gen",
|
||||
"roc_gen_llvm",
|
||||
"roc_load",
|
||||
"roc_module",
|
||||
"roc_mono",
|
||||
|
@ -3158,41 +3158,6 @@ dependencies = [
|
|||
"roc_region",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roc_gen"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"either",
|
||||
"im 14.3.0",
|
||||
"im-rc 14.3.0",
|
||||
"indoc 0.3.6",
|
||||
"inkwell 0.1.0",
|
||||
"inlinable_string",
|
||||
"libc",
|
||||
"maplit",
|
||||
"pretty_assertions 0.5.1",
|
||||
"quickcheck 0.8.5",
|
||||
"quickcheck_macros 0.8.0",
|
||||
"roc_build",
|
||||
"roc_builtins",
|
||||
"roc_can",
|
||||
"roc_collections",
|
||||
"roc_load",
|
||||
"roc_module",
|
||||
"roc_mono",
|
||||
"roc_parse",
|
||||
"roc_problem",
|
||||
"roc_region",
|
||||
"roc_reporting",
|
||||
"roc_solve",
|
||||
"roc_std",
|
||||
"roc_types",
|
||||
"roc_unify",
|
||||
"target-lexicon",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roc_gen_dev"
|
||||
version = "0.1.0"
|
||||
|
@ -3231,6 +3196,41 @@ dependencies = [
|
|||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roc_gen_llvm"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"either",
|
||||
"im 14.3.0",
|
||||
"im-rc 14.3.0",
|
||||
"indoc 0.3.6",
|
||||
"inkwell 0.1.0",
|
||||
"inlinable_string",
|
||||
"libc",
|
||||
"maplit",
|
||||
"pretty_assertions 0.5.1",
|
||||
"quickcheck 0.8.5",
|
||||
"quickcheck_macros 0.8.0",
|
||||
"roc_build",
|
||||
"roc_builtins",
|
||||
"roc_can",
|
||||
"roc_collections",
|
||||
"roc_load",
|
||||
"roc_module",
|
||||
"roc_mono",
|
||||
"roc_parse",
|
||||
"roc_problem",
|
||||
"roc_region",
|
||||
"roc_reporting",
|
||||
"roc_solve",
|
||||
"roc_std",
|
||||
"roc_types",
|
||||
"roc_unify",
|
||||
"target-lexicon",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roc_load"
|
||||
version = "0.1.0"
|
||||
|
@ -3910,7 +3910,7 @@ dependencies = [
|
|||
"roc_can",
|
||||
"roc_collections",
|
||||
"roc_constrain",
|
||||
"roc_gen",
|
||||
"roc_gen_llvm",
|
||||
"roc_load",
|
||||
"roc_module",
|
||||
"roc_mono",
|
||||
|
|
|
@ -17,7 +17,7 @@ members = [
|
|||
"compiler/test_mono_macros",
|
||||
"compiler/test_mono",
|
||||
"compiler/load",
|
||||
"compiler/gen",
|
||||
"compiler/gen_llvm",
|
||||
"compiler/gen_dev",
|
||||
"compiler/build",
|
||||
"compiler/arena_pool",
|
||||
|
@ -32,6 +32,12 @@ members = [
|
|||
"roc_std",
|
||||
"docs"
|
||||
]
|
||||
# Needed to be able to run `cargo run -p roc_cli --no-default-features` -
|
||||
# see www/build.sh for more.
|
||||
#
|
||||
# Without the `-p` flag, cargo ignores `--no-default-features` when you have a
|
||||
# workspace, and without `resolver = "2"` here, you can't use `-p` like this.
|
||||
resolver = "2"
|
||||
|
||||
# Optimizations based on https://deterministic.space/high-performance-rust.html
|
||||
[profile.release]
|
||||
|
|
|
@ -115,6 +115,7 @@ bench-roc:
|
|||
FROM +copy-dirs-and-cache
|
||||
ENV RUST_BACKTRACE=full
|
||||
RUN cargo criterion -V
|
||||
# ulimit -s unlimited to prevent stack overflow errors for CFold
|
||||
RUN --privileged --mount=type=cache,target=$SCCACHE_DIR \
|
||||
cd cli && cargo criterion && sccache --show-stats
|
||||
ulimit -s unlimited && cd cli && cargo criterion && sccache --show-stats
|
||||
|
||||
|
|
|
@ -15,7 +15,12 @@ test = false
|
|||
bench = false
|
||||
|
||||
[features]
|
||||
default = ["target-x86"]
|
||||
default = ["target-x86", "llvm", "editor"]
|
||||
|
||||
# This is a separate feature because when we generate docs on Netlify,
|
||||
# it doesn't have LLVM installed. (Also, it doesn't need to do code gen.)
|
||||
llvm = ["inkwell", "roc_gen_llvm", "roc_build/llvm"]
|
||||
editor = ["roc_editor"]
|
||||
|
||||
target-x86 = []
|
||||
|
||||
|
@ -45,11 +50,11 @@ roc_unify = { path = "../compiler/unify" }
|
|||
roc_solve = { path = "../compiler/solve" }
|
||||
roc_mono = { path = "../compiler/mono" }
|
||||
roc_load = { path = "../compiler/load" }
|
||||
roc_gen = { path = "../compiler/gen" }
|
||||
roc_build = { path = "../compiler/build" }
|
||||
roc_gen_llvm = { path = "../compiler/gen_llvm", optional = true }
|
||||
roc_build = { path = "../compiler/build", default-features = false }
|
||||
roc_fmt = { path = "../compiler/fmt" }
|
||||
roc_reporting = { path = "../compiler/reporting" }
|
||||
roc_editor = { path = "../editor" }
|
||||
roc_editor = { path = "../editor", optional = true }
|
||||
# TODO switch to clap 3.0.0 once it's out. Tried adding clap = "~3.0.0-beta.1" and cargo wouldn't accept it
|
||||
clap = { git = "https://github.com/rtfeldman/clap", branch = "master" }
|
||||
const_format = "0.2.8"
|
||||
|
@ -62,7 +67,7 @@ inlinable_string = "0.1"
|
|||
libc = "0.2"
|
||||
libloading = "0.6"
|
||||
|
||||
inkwell = { path = "../vendor/inkwell" }
|
||||
inkwell = { path = "../vendor/inkwell", optional = true }
|
||||
target-lexicon = "0.10"
|
||||
tempfile = "3.1.0"
|
||||
|
||||
|
|
17
cli/benches/README.md
Normal file
17
cli/benches/README.md
Normal file
|
@ -0,0 +1,17 @@
|
|||
|
||||
# Running the benchmarks
|
||||
|
||||
Install cargo criterion:
|
||||
```
|
||||
cargo install cargo-criterion
|
||||
```
|
||||
|
||||
To prevent stack overflow on the `CFold` benchmark:
|
||||
```
|
||||
ulimit -s unlimited
|
||||
```
|
||||
|
||||
In the `cli` folder execute:
|
||||
```
|
||||
cargo criterion
|
||||
```
|
|
@ -1,5 +1,5 @@
|
|||
use cli_utils::bench_utils::{
|
||||
bench_cfold, bench_deriv, bench_nqueens, bench_rbtree_ck, bench_rbtree_delete,
|
||||
bench_cfold, bench_deriv, bench_nqueens, bench_quicksort, bench_rbtree_ck, bench_rbtree_delete,
|
||||
};
|
||||
use criterion::{
|
||||
criterion_group, criterion_main, measurement::WallTime, BenchmarkGroup, Criterion, SamplingMode,
|
||||
|
@ -7,17 +7,17 @@ use criterion::{
|
|||
|
||||
fn bench_group_wall_time(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("bench-group_wall-time");
|
||||
// calculate statistics based on a fixed(flat) 100 runs
|
||||
// calculate statistics based on a fixed(flat) 200 runs
|
||||
group.sampling_mode(SamplingMode::Flat);
|
||||
group.sample_size(200);
|
||||
|
||||
let bench_funcs: Vec<fn(Option<&mut BenchmarkGroup<WallTime>>) -> ()> = vec![
|
||||
bench_nqueens, // queens 11
|
||||
bench_cfold, // e = mkExpr 12 1
|
||||
bench_deriv, // nest deriv 7 f
|
||||
bench_rbtree_ck, // ms = makeMap 5 5600
|
||||
bench_rbtree_delete, // m = makeMap 6000
|
||||
// TODO quicksort
|
||||
bench_nqueens, // queens 11
|
||||
bench_cfold, // e = mkExpr 17 1
|
||||
bench_deriv, // nest deriv 8 f
|
||||
bench_rbtree_ck, // ms = makeMap 5 80000
|
||||
bench_rbtree_delete, // m = makeMap 100000
|
||||
bench_quicksort, // list size 10000
|
||||
];
|
||||
|
||||
for bench_func in bench_funcs.iter() {
|
||||
|
|
File diff suppressed because one or more lines are too long
|
@ -5,8 +5,8 @@ use roc_build::{
|
|||
};
|
||||
use roc_can::builtins::builtin_defs_map;
|
||||
use roc_collections::all::MutMap;
|
||||
use roc_gen::llvm::build::OptLevel;
|
||||
use roc_load::file::LoadingProblem;
|
||||
use roc_mono::ir::OptLevel;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, SystemTime};
|
||||
use target_lexicon::Triple;
|
||||
|
@ -32,6 +32,7 @@ pub struct BuiltFile {
|
|||
pub total_time: Duration,
|
||||
}
|
||||
|
||||
#[cfg(feature = "llvm")]
|
||||
pub fn build_file<'a>(
|
||||
arena: &'a Bump,
|
||||
target: &Triple,
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
#[macro_use]
|
||||
extern crate clap;
|
||||
|
||||
use build::{build_file, BuildOutcome, BuiltFile};
|
||||
use build::{BuildOutcome, BuiltFile};
|
||||
use bumpalo::Bump;
|
||||
use clap::{App, AppSettings, Arg, ArgMatches};
|
||||
use roc_build::link::LinkType;
|
||||
use roc_gen::llvm::build::OptLevel;
|
||||
use roc_load::file::LoadingProblem;
|
||||
use roc_mono::ir::OptLevel;
|
||||
use std::env;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
@ -116,7 +116,9 @@ pub enum BuildConfig {
|
|||
BuildAndRun { roc_file_arg_index: usize },
|
||||
}
|
||||
|
||||
#[cfg(feature = "llvm")]
|
||||
pub fn build(target: &Triple, matches: &ArgMatches, config: BuildConfig) -> io::Result<i32> {
|
||||
use build::build_file;
|
||||
use BuildConfig::*;
|
||||
|
||||
let arena = Bump::new();
|
||||
|
|
|
@ -1,17 +1,26 @@
|
|||
use roc_cli::{
|
||||
build, build_app, docs, repl, BuildConfig, CMD_BUILD, CMD_DOCS, CMD_EDIT, CMD_REPL, CMD_RUN,
|
||||
build_app, docs, repl, BuildConfig, CMD_BUILD, CMD_DOCS, CMD_EDIT, CMD_REPL, CMD_RUN,
|
||||
DIRECTORY_OR_FILES, ROC_FILE,
|
||||
};
|
||||
use std::fs::{self, FileType};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use target_lexicon::Triple;
|
||||
|
||||
#[cfg(feature = "llvm")]
|
||||
use roc_cli::build;
|
||||
|
||||
#[cfg(not(feature = "llvm"))]
|
||||
fn build(_target: &Triple, _matches: &clap::ArgMatches, _config: BuildConfig) -> io::Result<i32> {
|
||||
panic!("Building without LLVM is not currently supported.");
|
||||
}
|
||||
|
||||
fn main() -> io::Result<()> {
|
||||
let matches = build_app().get_matches();
|
||||
|
||||
let exit_code = match matches.subcommand_name() {
|
||||
None => {
|
||||
roc_editor::launch(&[])?;
|
||||
launch_editor(&[])?;
|
||||
|
||||
// rustc couldn't infer the error type here
|
||||
Result::<i32, io::Error>::Ok(0)
|
||||
|
@ -44,14 +53,14 @@ fn main() -> io::Result<()> {
|
|||
.values_of_os(DIRECTORY_OR_FILES)
|
||||
{
|
||||
None => {
|
||||
roc_editor::launch(&[])?;
|
||||
launch_editor(&[])?;
|
||||
}
|
||||
Some(values) => {
|
||||
let paths = values
|
||||
.map(|os_str| Path::new(os_str))
|
||||
.collect::<Vec<&Path>>();
|
||||
|
||||
roc_editor::launch(&paths)?;
|
||||
launch_editor(&paths)?;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -65,11 +74,16 @@ fn main() -> io::Result<()> {
|
|||
.values_of_os(DIRECTORY_OR_FILES)
|
||||
.unwrap();
|
||||
|
||||
let paths = values
|
||||
.map(|os_str| Path::new(os_str).to_path_buf())
|
||||
.collect::<Vec<PathBuf>>();
|
||||
let mut roc_files = Vec::new();
|
||||
|
||||
docs(paths);
|
||||
// Populate roc_files
|
||||
for os_str in values {
|
||||
let metadata = fs::metadata(os_str)?;
|
||||
|
||||
roc_files_recursive(os_str, metadata.file_type(), &mut roc_files)?;
|
||||
}
|
||||
|
||||
docs(roc_files);
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
|
@ -78,3 +92,31 @@ fn main() -> io::Result<()> {
|
|||
|
||||
std::process::exit(exit_code);
|
||||
}
|
||||
|
||||
fn roc_files_recursive<P: AsRef<Path>>(
|
||||
path: P,
|
||||
file_type: FileType,
|
||||
roc_files: &mut Vec<PathBuf>,
|
||||
) -> io::Result<()> {
|
||||
if file_type.is_dir() {
|
||||
for entry_res in fs::read_dir(path)? {
|
||||
let entry = entry_res?;
|
||||
|
||||
roc_files_recursive(entry.path(), entry.file_type()?, roc_files)?;
|
||||
}
|
||||
} else {
|
||||
roc_files.push(path.as_ref().to_path_buf());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "editor")]
|
||||
fn launch_editor(filepaths: &[&Path]) -> io::Result<()> {
|
||||
roc_editor::launch(filepaths)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "editor"))]
|
||||
fn launch_editor(_filepaths: &[&Path]) -> io::Result<()> {
|
||||
panic!("Cannot launch the editor because this build of roc did not include `feature = \"editor\"`!");
|
||||
}
|
||||
|
|
|
@ -1,15 +1,12 @@
|
|||
use const_format::concatcp;
|
||||
#[cfg(feature = "llvm")]
|
||||
use gen::{gen_and_eval, ReplOutput};
|
||||
use roc_gen::llvm::build::OptLevel;
|
||||
use roc_parse::parser::{EExpr, SyntaxError};
|
||||
use rustyline::error::ReadlineError;
|
||||
use rustyline::highlight::{Highlighter, PromptInfo};
|
||||
use rustyline::validate::{self, ValidationContext, ValidationResult, Validator};
|
||||
use rustyline::Editor;
|
||||
use rustyline_derive::{Completer, Helper, Hinter};
|
||||
use std::borrow::Cow;
|
||||
use std::io;
|
||||
use target_lexicon::Triple;
|
||||
|
||||
const BLUE: &str = "\u{001b}[36m";
|
||||
const PINK: &str = "\u{001b}[35m";
|
||||
|
@ -30,7 +27,9 @@ pub const INSTRUCTIONS: &str = "Enter an expression, or :help, or :exit/:q.\n";
|
|||
pub const PROMPT: &str = concatcp!("\n", BLUE, "»", END_COL, " ");
|
||||
pub const CONT_PROMPT: &str = concatcp!(BLUE, "…", END_COL, " ");
|
||||
|
||||
#[cfg(feature = "llvm")]
|
||||
mod eval;
|
||||
#[cfg(feature = "llvm")]
|
||||
mod gen;
|
||||
|
||||
#[derive(Completer, Helper, Hinter)]
|
||||
|
@ -107,7 +106,16 @@ impl Validator for InputValidator {
|
|||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "llvm"))]
|
||||
pub fn main() -> io::Result<()> {
|
||||
panic!("The REPL currently requires being built with LLVM.");
|
||||
}
|
||||
|
||||
#[cfg(feature = "llvm")]
|
||||
pub fn main() -> io::Result<()> {
|
||||
use rustyline::error::ReadlineError;
|
||||
use rustyline::Editor;
|
||||
|
||||
// To debug rustyline:
|
||||
// <UNCOMMENT> env_logger::init();
|
||||
// <RUN WITH:> RUST_LOG=rustyline=debug cargo run repl 2> debug.log
|
||||
|
@ -226,7 +234,11 @@ fn report_parse_error(fail: SyntaxError) {
|
|||
println!("TODO Gracefully report parse error in repl: {:?}", fail);
|
||||
}
|
||||
|
||||
#[cfg(feature = "llvm")]
|
||||
fn eval_and_format<'a>(src: &str) -> Result<String, SyntaxError<'a>> {
|
||||
use roc_mono::ir::OptLevel;
|
||||
use target_lexicon::Triple;
|
||||
|
||||
gen_and_eval(src.as_bytes(), Triple::host(), OptLevel::Normal).map(|output| match output {
|
||||
ReplOutput::NoProblems { expr, expr_type } => {
|
||||
format!("\n{} {}:{} {}", expr, PINK, END_COL, expr_type)
|
||||
|
|
|
@ -2,7 +2,7 @@ use bumpalo::collections::Vec;
|
|||
use bumpalo::Bump;
|
||||
use libloading::Library;
|
||||
use roc_collections::all::MutMap;
|
||||
use roc_gen::{run_jit_function, run_jit_function_dynamic_type};
|
||||
use roc_gen_llvm::{run_jit_function, run_jit_function_dynamic_type};
|
||||
use roc_module::ident::{Lowercase, TagName};
|
||||
use roc_module::operator::CalledVia;
|
||||
use roc_module::symbol::{Interns, ModuleId, Symbol};
|
||||
|
|
|
@ -8,9 +8,9 @@ use roc_can::builtins::builtin_defs_map;
|
|||
use roc_collections::all::{MutMap, MutSet};
|
||||
use roc_fmt::annotation::Formattable;
|
||||
use roc_fmt::annotation::{Newlines, Parens};
|
||||
use roc_gen::llvm::build::OptLevel;
|
||||
use roc_gen::llvm::externs::add_default_roc_externs;
|
||||
use roc_gen_llvm::llvm::externs::add_default_roc_externs;
|
||||
use roc_load::file::LoadingProblem;
|
||||
use roc_mono::ir::OptLevel;
|
||||
use roc_parse::parser::SyntaxError;
|
||||
use roc_types::pretty_print::{content_to_string, name_all_type_vars};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
@ -130,7 +130,9 @@ pub fn gen_and_eval<'a>(
|
|||
let context = Context::create();
|
||||
let builder = context.create_builder();
|
||||
let ptr_bytes = target.pointer_width().unwrap().bytes() as u32;
|
||||
let module = arena.alloc(roc_gen::llvm::build::module_from_builtins(&context, ""));
|
||||
let module = arena.alloc(roc_gen_llvm::llvm::build::module_from_builtins(
|
||||
&context, "",
|
||||
));
|
||||
|
||||
// Add roc_alloc, roc_realloc, and roc_dealloc, since the repl has no
|
||||
// platform to provide them.
|
||||
|
@ -166,12 +168,12 @@ pub fn gen_and_eval<'a>(
|
|||
|
||||
let module = arena.alloc(module);
|
||||
let (module_pass, function_pass) =
|
||||
roc_gen::llvm::build::construct_optimization_passes(module, opt_level);
|
||||
roc_gen_llvm::llvm::build::construct_optimization_passes(module, opt_level);
|
||||
|
||||
let (dibuilder, compile_unit) = roc_gen::llvm::build::Env::new_debug_info(module);
|
||||
let (dibuilder, compile_unit) = roc_gen_llvm::llvm::build::Env::new_debug_info(module);
|
||||
|
||||
// Compile and add all the Procs before adding main
|
||||
let env = roc_gen::llvm::build::Env {
|
||||
let env = roc_gen_llvm::llvm::build::Env {
|
||||
arena: &arena,
|
||||
builder: &builder,
|
||||
dibuilder: &dibuilder,
|
||||
|
@ -185,7 +187,7 @@ pub fn gen_and_eval<'a>(
|
|||
exposed_to_host: MutSet::default(),
|
||||
};
|
||||
|
||||
let (main_fn_name, main_fn) = roc_gen::llvm::build::build_procedures_return_main(
|
||||
let (main_fn_name, main_fn) = roc_gen_llvm::llvm::build::build_procedures_return_main(
|
||||
&env,
|
||||
opt_level,
|
||||
procedures,
|
||||
|
|
|
@ -7,7 +7,7 @@ extern crate indoc;
|
|||
#[cfg(test)]
|
||||
mod repl_eval {
|
||||
use cli_utils::helpers;
|
||||
use roc_gen::run_roc::RocCallResult;
|
||||
use roc_gen_llvm::run_roc::RocCallResult;
|
||||
|
||||
#[test]
|
||||
fn check_discriminant_size() {
|
||||
|
@ -16,7 +16,8 @@ mod repl_eval {
|
|||
let value: i64 = 1234;
|
||||
assert_eq!(
|
||||
std::mem::size_of_val(&RocCallResult::Success(value)),
|
||||
roc_gen::run_roc::ROC_CALL_RESULT_DISCRIMINANT_SIZE + std::mem::size_of_val(&value)
|
||||
roc_gen_llvm::run_roc::ROC_CALL_RESULT_DISCRIMINANT_SIZE
|
||||
+ std::mem::size_of_val(&value)
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
@ -19,7 +19,7 @@ roc_unify = { path = "../unify" }
|
|||
roc_solve = { path = "../solve" }
|
||||
roc_mono = { path = "../mono" }
|
||||
roc_load = { path = "../load" }
|
||||
roc_gen = { path = "../gen" }
|
||||
roc_gen_llvm = { path = "../gen_llvm", optional = true }
|
||||
roc_reporting = { path = "../reporting" }
|
||||
im = "14" # im and im-rc should always have the same version!
|
||||
im-rc = "14" # im and im-rc should always have the same version!
|
||||
|
@ -28,7 +28,7 @@ inlinable_string = "0.1.0"
|
|||
libloading = "0.6"
|
||||
tempfile = "3.1.0"
|
||||
serde_json = "1.0"
|
||||
inkwell = { path = "../../vendor/inkwell" }
|
||||
inkwell = { path = "../../vendor/inkwell", optional = true }
|
||||
target-lexicon = "0.10"
|
||||
|
||||
[dev-dependencies]
|
||||
|
@ -39,6 +39,10 @@ quickcheck = "0.8"
|
|||
quickcheck_macros = "0.8"
|
||||
|
||||
[features]
|
||||
default = ["llvm"]
|
||||
target-arm = []
|
||||
target-aarch64 = []
|
||||
target-webassembly = []
|
||||
# This is a separate feature because when we generate docs on Netlify,
|
||||
# it doesn't have LLVM installed. (Also, it doesn't need to do code gen.)
|
||||
llvm = ["inkwell", "roc_gen_llvm"]
|
||||
|
|
|
@ -1,16 +1,14 @@
|
|||
use crate::target;
|
||||
use crate::target::arch_str;
|
||||
use inkwell::module::Module;
|
||||
use inkwell::targets::{CodeModel, FileType, RelocMode};
|
||||
#[cfg(feature = "llvm")]
|
||||
use libloading::{Error, Library};
|
||||
use roc_gen::llvm::build::OptLevel;
|
||||
#[cfg(feature = "llvm")]
|
||||
use roc_mono::ir::OptLevel;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Output};
|
||||
use target_lexicon::{Architecture, OperatingSystem, Triple};
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum LinkType {
|
||||
|
@ -360,6 +358,9 @@ fn link_linux(
|
|||
};
|
||||
|
||||
let env_path = env::var("PATH").unwrap_or_else(|_| "".to_string());
|
||||
|
||||
init_arch(target);
|
||||
|
||||
// NOTE: order of arguments to `ld` matters here!
|
||||
// The `-l` flags should go after the `.o` arguments
|
||||
Ok((
|
||||
|
@ -477,12 +478,16 @@ fn link_macos(
|
|||
))
|
||||
}
|
||||
|
||||
#[cfg(feature = "llvm")]
|
||||
pub fn module_to_dylib(
|
||||
module: &Module,
|
||||
module: &inkwell::module::Module,
|
||||
target: &Triple,
|
||||
opt_level: OptLevel,
|
||||
) -> Result<Library, Error> {
|
||||
let dir = tempdir().unwrap();
|
||||
use crate::target::{self, convert_opt_level};
|
||||
use inkwell::targets::{CodeModel, FileType, RelocMode};
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let filename = PathBuf::from("Test.roc");
|
||||
let file_path = dir.path().join(filename);
|
||||
let mut app_o_file = file_path;
|
||||
|
@ -492,7 +497,8 @@ pub fn module_to_dylib(
|
|||
// Emit the .o file using position-indepedent code (PIC) - needed for dylibs
|
||||
let reloc = RelocMode::PIC;
|
||||
let model = CodeModel::Default;
|
||||
let target_machine = target::target_machine(target, opt_level.into(), reloc, model).unwrap();
|
||||
let target_machine =
|
||||
target::target_machine(target, convert_opt_level(opt_level), reloc, model).unwrap();
|
||||
|
||||
target_machine
|
||||
.write_to_file(module, FileType::Object, &app_o_file)
|
||||
|
@ -529,3 +535,13 @@ fn validate_output(file_name: &str, cmd_name: &str, output: Output) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "llvm")]
|
||||
fn init_arch(target: &Triple) {
|
||||
crate::target::init_arch(target);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "llvm"))]
|
||||
fn init_arch(_target: &Triple) {
|
||||
panic!("Tried to initialize LLVM when crate was not built with `feature = \"llvm\"` enabled");
|
||||
}
|
||||
|
|
|
@ -1,13 +1,14 @@
|
|||
use crate::target;
|
||||
use bumpalo::Bump;
|
||||
use inkwell::context::Context;
|
||||
use inkwell::targets::{CodeModel, FileType, RelocMode};
|
||||
pub use roc_gen::llvm::build::FunctionIterator;
|
||||
use roc_gen::llvm::build::{module_from_builtins, OptLevel};
|
||||
#[cfg(feature = "llvm")]
|
||||
use roc_gen_llvm::llvm::build::module_from_builtins;
|
||||
#[cfg(feature = "llvm")]
|
||||
pub use roc_gen_llvm::llvm::build::FunctionIterator;
|
||||
#[cfg(feature = "llvm")]
|
||||
use roc_load::file::MonomorphizedModule;
|
||||
#[cfg(feature = "llvm")]
|
||||
use roc_mono::ir::OptLevel;
|
||||
#[cfg(feature = "llvm")]
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
use target_lexicon::Triple;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct CodeGenTiming {
|
||||
|
@ -18,16 +19,24 @@ pub struct CodeGenTiming {
|
|||
// TODO how should imported modules factor into this? What if those use builtins too?
|
||||
// TODO this should probably use more helper functions
|
||||
// TODO make this polymorphic in the llvm functions so it can be reused for another backend.
|
||||
#[cfg(feature = "llvm")]
|
||||
#[allow(clippy::cognitive_complexity)]
|
||||
pub fn gen_from_mono_module(
|
||||
arena: &Bump,
|
||||
arena: &bumpalo::Bump,
|
||||
mut loaded: MonomorphizedModule,
|
||||
roc_file_path: &Path,
|
||||
target: Triple,
|
||||
target: target_lexicon::Triple,
|
||||
app_o_file: &Path,
|
||||
opt_level: OptLevel,
|
||||
emit_debug_info: bool,
|
||||
) -> CodeGenTiming {
|
||||
use crate::target::{self, convert_opt_level};
|
||||
use inkwell::attributes::{Attribute, AttributeLoc};
|
||||
use inkwell::context::Context;
|
||||
use inkwell::module::Linkage;
|
||||
use inkwell::targets::{CodeModel, FileType, RelocMode};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use roc_reporting::report::{
|
||||
can_problem, mono_problem, type_problem, RocDocAllocator, DEFAULT_PALETTE,
|
||||
};
|
||||
|
@ -87,9 +96,6 @@ pub fn gen_from_mono_module(
|
|||
// module.strip_debug_info();
|
||||
|
||||
// mark our zig-defined builtins as internal
|
||||
use inkwell::attributes::{Attribute, AttributeLoc};
|
||||
use inkwell::module::Linkage;
|
||||
|
||||
let app_ll_file = {
|
||||
let mut temp = PathBuf::from(roc_file_path);
|
||||
temp.set_extension("ll");
|
||||
|
@ -119,12 +125,12 @@ pub fn gen_from_mono_module(
|
|||
}
|
||||
|
||||
let builder = context.create_builder();
|
||||
let (dibuilder, compile_unit) = roc_gen::llvm::build::Env::new_debug_info(module);
|
||||
let (mpm, _fpm) = roc_gen::llvm::build::construct_optimization_passes(module, opt_level);
|
||||
let (dibuilder, compile_unit) = roc_gen_llvm::llvm::build::Env::new_debug_info(module);
|
||||
let (mpm, _fpm) = roc_gen_llvm::llvm::build::construct_optimization_passes(module, opt_level);
|
||||
|
||||
// Compile and add all the Procs before adding main
|
||||
let ptr_bytes = target.pointer_width().unwrap().bytes() as u32;
|
||||
let env = roc_gen::llvm::build::Env {
|
||||
let env = roc_gen_llvm::llvm::build::Env {
|
||||
arena: &arena,
|
||||
builder: &builder,
|
||||
dibuilder: &dibuilder,
|
||||
|
@ -137,7 +143,7 @@ pub fn gen_from_mono_module(
|
|||
exposed_to_host: loaded.exposed_to_host.keys().copied().collect(),
|
||||
};
|
||||
|
||||
roc_gen::llvm::build::build_procedures(&env, opt_level, loaded.procedures);
|
||||
roc_gen_llvm::llvm::build::build_procedures(&env, opt_level, loaded.procedures);
|
||||
|
||||
env.dibuilder.finalize();
|
||||
|
||||
|
@ -226,7 +232,7 @@ pub fn gen_from_mono_module(
|
|||
let reloc = RelocMode::Default;
|
||||
let model = CodeModel::Default;
|
||||
let target_machine =
|
||||
target::target_machine(&target, opt_level.into(), reloc, model).unwrap();
|
||||
target::target_machine(&target, convert_opt_level(opt_level), reloc, model).unwrap();
|
||||
|
||||
target_machine
|
||||
.write_to_file(&env.module, FileType::Object, &app_o_file)
|
||||
|
|
|
@ -1,7 +1,10 @@
|
|||
use inkwell::targets::{
|
||||
CodeModel, InitializationConfig, RelocMode, Target, TargetMachine, TargetTriple,
|
||||
#[cfg(feature = "llvm")]
|
||||
use inkwell::{
|
||||
targets::{CodeModel, InitializationConfig, RelocMode, Target, TargetMachine, TargetTriple},
|
||||
OptimizationLevel,
|
||||
};
|
||||
use inkwell::OptimizationLevel;
|
||||
#[cfg(feature = "llvm")]
|
||||
use roc_mono::ir::OptLevel;
|
||||
use target_lexicon::{Architecture, OperatingSystem, Triple};
|
||||
|
||||
pub fn target_triple_str(target: &Triple) -> &'static str {
|
||||
|
@ -28,36 +31,20 @@ pub fn target_triple_str(target: &Triple) -> &'static str {
|
|||
}
|
||||
}
|
||||
|
||||
/// NOTE: arch_str is *not* the same as the beginning of the magic target triple
|
||||
/// string! For example, if it's "x86-64" here, the magic target triple string
|
||||
/// will begin with "x86_64" (with an underscore) instead.
|
||||
pub fn arch_str(target: &Triple) -> &'static str {
|
||||
// Best guide I've found on how to determine these magic strings:
|
||||
//
|
||||
// https://stackoverflow.com/questions/15036909/clang-how-to-list-supported-target-architectures
|
||||
#[cfg(feature = "llvm")]
|
||||
pub fn init_arch(target: &Triple) {
|
||||
match target.architecture {
|
||||
Architecture::X86_64 => {
|
||||
Target::initialize_x86(&InitializationConfig::default());
|
||||
|
||||
"x86-64"
|
||||
}
|
||||
Architecture::Aarch64(_) if cfg!(feature = "target-aarch64") => {
|
||||
Target::initialize_aarch64(&InitializationConfig::default());
|
||||
"aarch64"
|
||||
}
|
||||
Architecture::Arm(_) if cfg!(feature = "target-arm") => {
|
||||
// NOTE: why not enable arm and wasm by default?
|
||||
//
|
||||
// We had some trouble getting them to link properly. This may be resolved in the
|
||||
// future, or maybe it was just some weird configuration on one machine.
|
||||
Target::initialize_arm(&InitializationConfig::default());
|
||||
|
||||
"arm"
|
||||
}
|
||||
Architecture::Wasm32 if cfg!(feature = "target-webassembly") => {
|
||||
Target::initialize_webassembly(&InitializationConfig::default());
|
||||
|
||||
"wasm32"
|
||||
}
|
||||
_ => panic!(
|
||||
"TODO gracefully handle unsupported target architecture: {:?}",
|
||||
|
@ -66,6 +53,26 @@ pub fn arch_str(target: &Triple) -> &'static str {
|
|||
}
|
||||
}
|
||||
|
||||
/// NOTE: arch_str is *not* the same as the beginning of the magic target triple
|
||||
/// string! For example, if it's "x86-64" here, the magic target triple string
|
||||
/// will begin with "x86_64" (with an underscore) instead.
|
||||
pub fn arch_str(target: &Triple) -> &'static str {
|
||||
// Best guide I've found on how to determine these magic strings:
|
||||
//
|
||||
// https://stackoverflow.com/questions/15036909/clang-how-to-list-supported-target-architectures
|
||||
match target.architecture {
|
||||
Architecture::X86_64 => "x86-64",
|
||||
Architecture::Aarch64(_) if cfg!(feature = "target-aarch64") => "aarch64",
|
||||
Architecture::Arm(_) if cfg!(feature = "target-arm") => "arm",
|
||||
Architecture::Wasm32 if cfg!(feature = "target-webassembly") => "wasm32",
|
||||
_ => panic!(
|
||||
"TODO gracefully handle unsupported target architecture: {:?}",
|
||||
target.architecture
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "llvm")]
|
||||
pub fn target_machine(
|
||||
target: &Triple,
|
||||
opt: OptimizationLevel,
|
||||
|
@ -74,6 +81,8 @@ pub fn target_machine(
|
|||
) -> Option<TargetMachine> {
|
||||
let arch = arch_str(target);
|
||||
|
||||
init_arch(target);
|
||||
|
||||
Target::from_name(arch).unwrap().create_target_machine(
|
||||
&TargetTriple::create(target_triple_str(target)),
|
||||
"generic",
|
||||
|
@ -83,3 +92,11 @@ pub fn target_machine(
|
|||
model,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "llvm")]
|
||||
pub fn convert_opt_level(level: OptLevel) -> OptimizationLevel {
|
||||
match level {
|
||||
OptLevel::Normal => OptimizationLevel::None,
|
||||
OptLevel::Optimize => OptimizationLevel::Aggressive,
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,15 +9,15 @@ Towards the bottom of `symbol.rs` there is a `define_builtins!` macro being used
|
|||
Some of these have `#` inside their name (`first#list`, `#lt` ..). This is a trick we are doing to hide implementation details from Roc programmers. To a Roc programmer, a name with `#` in it is invalid, because `#` means everything after it is parsed to a comment. We are constructing these functions manually, so we are circumventing the parsing step and dont have such restrictions. We get to make functions and values with `#` which as a consequence are not accessible to Roc programmers. Roc programmers simply cannot reference them.
|
||||
|
||||
But we can use these values and some of these are necessary for implementing builtins. For example, `List.get` returns tags, and it is not easy for us to create tags when composing LLVM. What is easier however, is:
|
||||
- ..writing `List.#getUnsafe` that has the dangerous signature of `List elem, Int -> elem` in LLVM
|
||||
- ..writing `List elem, Int -> Result elem [ OutOfBounds ]*` in a type safe way that uses `getUnsafe` internally, only after it checks if the `elem` at `Int` index exists.
|
||||
- ..writing `List.#getUnsafe` that has the dangerous signature of `List elem, Nat -> elem` in LLVM
|
||||
- ..writing `List elem, Nat -> Result elem [ OutOfBounds ]*` in a type safe way that uses `getUnsafe` internally, only after it checks if the `elem` at `Nat` index exists.
|
||||
|
||||
|
||||
### can/src/builtins.rs
|
||||
|
||||
Right at the top of this module is a function called `builtin_defs`. All this is doing is mapping the `Symbol` defined in `module/src/symbol.rs` to its implementation. Some of the builtins are quite complex, such as `list_get`. What makes `list_get` is that it returns tags, and in order to return tags it first has to defer to lower-level functions via an if statement.
|
||||
|
||||
Lets look at `List.repeat : elem, Int -> List elem`, which is more straight-forward, and points directly to its lower level implementation:
|
||||
Lets look at `List.repeat : elem, Nat -> List elem`, which is more straight-forward, and points directly to its lower level implementation:
|
||||
```
|
||||
fn list_repeat(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
let elem_var = var_store.fresh();
|
||||
|
|
|
@ -9,6 +9,20 @@ use std::str;
|
|||
|
||||
fn main() {
|
||||
let out_dir = env::var_os("OUT_DIR").unwrap();
|
||||
let dest_obj_path = Path::new(&out_dir).join("builtins.o");
|
||||
let dest_obj = dest_obj_path.to_str().expect("Invalid dest object path");
|
||||
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rustc-env=BUILTINS_O={}", dest_obj);
|
||||
|
||||
// When we build on Netlify, zig is not installed (but also not used,
|
||||
// since all we're doing is generating docs), so we can skip the steps
|
||||
// that require having zig installed.
|
||||
if env::var_os("NO_ZIG_INSTALLED").is_some() {
|
||||
// We still need to do the other things before this point, because
|
||||
// setting the env vars is needed for other parts of the build.
|
||||
return;
|
||||
}
|
||||
|
||||
let big_sur_path = "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/lib";
|
||||
let use_build_script = Path::new(big_sur_path).exists();
|
||||
|
@ -34,8 +48,6 @@ fn main() {
|
|||
run_command(&bitcode_path, "zig", &["build", "ir", "-Drelease=true"]);
|
||||
}
|
||||
|
||||
let dest_obj_path = Path::new(&out_dir).join("builtins.o");
|
||||
let dest_obj = dest_obj_path.to_str().expect("Invalid dest object path");
|
||||
println!("Moving zig object to: {}", dest_obj);
|
||||
|
||||
run_command(&bitcode_path, "mv", &[src_obj, dest_obj]);
|
||||
|
@ -50,8 +62,6 @@ fn main() {
|
|||
&[dest_ir, "-o", dest_bc],
|
||||
);
|
||||
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rustc-env=BUILTINS_O={}", dest_obj);
|
||||
get_zig_files(bitcode_path.as_path(), &|path| {
|
||||
let path: &Path = path;
|
||||
println!(
|
||||
|
|
|
@ -55,36 +55,36 @@ and : Bool, Bool -> Bool
|
|||
##
|
||||
## In some languages, `&&` and `||` are special-cased in the compiler to skip
|
||||
## evaluating the expression after the operator under certain circumstances.
|
||||
## # In Roc, this is not the case. See the performance notes for #Bool.and for details.
|
||||
## # In Roc, this is not the case. See the performance notes for [Bool.and] for details.
|
||||
or : Bool, Bool -> Bool
|
||||
|
||||
## Exclusive or
|
||||
xor : Bool, Bool -> Bool
|
||||
|
||||
# TODO: removed `'` from signature because parser does not support it yet
|
||||
# Original signature: `isEq : 'val, 'val -> Bool`
|
||||
## Returns `True` if the two values are *structurally equal*, and `False` otherwise.
|
||||
##
|
||||
## `a == b` is shorthand for `Bool.isEq a b`
|
||||
##
|
||||
## Structural equality works as follows:
|
||||
##
|
||||
## 1. #Int and #Float values are equal if their numbers are equal.
|
||||
## 2. Records are equal if all their fields are equal.
|
||||
## 3. Global tags are equal if they are the same tag, and also their contents (if any) are equal.
|
||||
## 4. Private tags are equal if they are the same tag, in the same module, and also their contents (if any) are equal.
|
||||
## 5. Collections (#String, #List, #Map, #Set, and #Bytes) are equal if they are the same length, and also all their corresponding elements are equal.
|
||||
## 1. Global tags are equal if they are the same tag, and also their contents (if any) are equal.
|
||||
## 2. Private tags are equal if they are the same tag, in the same module, and also their contents (if any) are equal.
|
||||
## 3. Records are equal if all their fields are equal.
|
||||
## 4. Collections ([Str], [List], [Dict], and [Set]) are equal if they are the same length, and also all their corresponding elements are equal.
|
||||
## 5. [Num] values are equal if their numbers are equal, with one exception: if both arguments to `isEq` are *NaN*, then `isEq` returns `False`. See [Num.isNaN] for more about *NaN*.
|
||||
##
|
||||
## Note that `isEq` takes `'val` instead of `val`, which means `isEq` does not
|
||||
## accept arguments whose types contain functions.
|
||||
# TODO: removed `'` from signature because parser does not support it yet
|
||||
# Original signature: `isEq : 'val, 'val -> Bool`
|
||||
isEq : val, val -> Bool
|
||||
|
||||
## Calls #eq on the given values, then calls #not on the result.
|
||||
# TODO: removed `'` from signature because parser does not support it yet
|
||||
# Original signature: `isNotEq : 'val, 'val -> Bool`
|
||||
## Calls [isEq] on the given values, then calls [not] on the result.
|
||||
##
|
||||
## `a != b` is shorthand for `Bool.isNotEq a b`
|
||||
##
|
||||
## Note that `isNotEq` takes `'val` instead of `val`, which means `isNotEq` does not
|
||||
## accept arguments whose types contain functions.
|
||||
# TODO: removed `'` from signature because parser does not support it yet
|
||||
# Original signature: `isNotEq : 'val, 'val -> Bool`
|
||||
isNotEq : val, val -> Bool
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
interface Defaults
|
||||
exposes []
|
||||
imports [
|
||||
Dict.{ Dict },
|
||||
Set.{ Set },
|
||||
Num.{ Num, Int, Float }
|
||||
]
|
|
@ -19,3 +19,15 @@ map :
|
|||
Dict beforeKey beforeValue,
|
||||
({ key: beforeKey, value: beforeValue } -> { key: afterKey, value: afterValue })
|
||||
-> Dict afterKey afterValue
|
||||
|
||||
# DESIGN NOTES: The reason for panicking when given NaN is that:
|
||||
# * If we allowed NaN in, Dict.insert would no longer be idempotent.
|
||||
# * If we allowed NaN but overrode its semantics to make it feel like "NaN == NaN" we'd need isNaN checks in all hashing operations as well as all equality checks (during collision detection), not just insert. This would be much worse for performance than panicking on insert, which only requires one extra conditional on insert.
|
||||
# * It's obviously invalid; the whole point of NaN is that an error occurred. Giving a runtime error notifies you when this problem happens. Giving it only on insert is the best for performance, because it means you aren't paying for isNaN checks on lookups as well.
|
||||
|
||||
# TODO: removed `'` from signature because parser does not support it yet
|
||||
# Original signature: insert : Dict 'key val, 'key, val -> Dict 'key val
|
||||
## Make sure never to insert a key of *NaN* into a [Dict]! Becuase *NaN* is
|
||||
## defined to be unequal to *NaN*, inserting a *NaN* key results in an entry
|
||||
## that can never be retrieved or removed from the [Dict].
|
||||
insert : Dict key val, key, val -> Dict key val
|
||||
|
|
|
@ -62,7 +62,7 @@ interface List2
|
|||
## the same type. If you want to put a mix of #Int and #Str values into a list, try this:
|
||||
##
|
||||
## ```
|
||||
## mixedList : List [ IntElem Int, StrElem Str ]*
|
||||
## mixedList : List [ IntElem I64, StrElem Str ]*
|
||||
## mixedList = [ IntElem 1, IntElem 2, StrElem "a", StrElem "b" ]
|
||||
## ```
|
||||
##
|
||||
|
@ -232,9 +232,28 @@ reverse : List elem -> List elem
|
|||
|
||||
## Sorts a list using a function which specifies how two elements are ordered.
|
||||
##
|
||||
##
|
||||
## When sorting by numeric values, it's more efficient to use [sortAsc] or
|
||||
## [sortDesc] instead.
|
||||
sort : List elem, (elem, elem -> [ Lt, Eq, Gt ]) -> List elem
|
||||
|
||||
## Sorts a list in ascending order (lowest to highest), using a function which
|
||||
## specifies a way to represent each element as a number.
|
||||
##
|
||||
## This is more efficient than [sort] because it skips
|
||||
## calculating the `[ Lt, Eq, Gt ]` value and uses the number directly instead.
|
||||
##
|
||||
## To sort in descending order (highest to lowest), use [List.sortDesc] instead.
|
||||
sortAsc : List elem, (elem -> Num *) -> List elem
|
||||
|
||||
## Sorts a list in descending order (highest to lowest), using a function which
|
||||
## specifies a way to represent each element as a number.
|
||||
##
|
||||
## This is more efficient than [sort] because it skips
|
||||
## calculating the `[ Lt, Eq, Gt ]` value and uses the number directly instead.
|
||||
##
|
||||
## To sort in ascending order (lowest to highest), use [List.sortAsc] instead.
|
||||
sortDesc : List elem, (elem -> Num *) -> List elem
|
||||
|
||||
## Convert each element in the list to something new, by calling a conversion
|
||||
## function on each of them. Then return a new list of the converted values.
|
||||
##
|
||||
|
@ -248,7 +267,7 @@ map : List before, (before -> after) -> List after
|
|||
|
||||
## This works like #List.map, except it also passes the index
|
||||
## of the element to the conversion function.
|
||||
mapWithIndex : List before, (before, Int -> after) -> List after
|
||||
mapWithIndex : List before, (before, Nat -> after) -> List after
|
||||
|
||||
## This works like #List.map, except at any time you can return `Err` to
|
||||
## cancel the entire operation immediately, and return that #Err.
|
||||
|
@ -279,7 +298,7 @@ update : List elem, Nat, (elem -> elem) -> List elem
|
|||
|
||||
## A more flexible version of #List.update, which returns an "updater" function
|
||||
## that lets you delay performing the update until later.
|
||||
updater : List elem, Nat -> { elem, new : elem -> List elem }
|
||||
updater : List elem, Nat -> { elem, new : (elem -> List elem) }
|
||||
|
||||
## If all the elements in the list are #Ok, return a new list containing the
|
||||
## contents of those #Ok tags. If any elements are #Err, return #Err.
|
||||
|
@ -629,7 +648,7 @@ walk : List elem, { start : state, step : (state, elem -> state) } -> state
|
|||
|
||||
## Note that in other languages, `walkBackwards` is sometimes called `reduceRight`,
|
||||
## `fold`, `foldRight`, or `foldr`.
|
||||
walkBackwards : List elem, { start : state, step : (state, elem -> state ]) } -> state
|
||||
walkBackwards : List elem, { start : state, step : (state, elem -> state) } -> state
|
||||
|
||||
## Same as #List.walk, except you can stop walking early.
|
||||
##
|
||||
|
|
|
@ -9,13 +9,24 @@ interface Num2
|
|||
## This is useful for functions that can work on either, for example #Num.add, whose type is:
|
||||
##
|
||||
## ```
|
||||
## add : Num range, Num range -> Num range
|
||||
## add : Num a, Num a -> Num a
|
||||
## ```
|
||||
##
|
||||
## The number 1.5 technically has the type `Num FloatingPoint`, so when you pass two of them to `Num.add`, the answer you get is `3.0 : Num FloatingPoint`.
|
||||
## The number 1.5 technically has the type `Num (Fraction *)`, so when you pass
|
||||
## two of them to [Num.add], the answer you get is `3.0 : Num (Fraction *)`.
|
||||
#
|
||||
## Similarly, the number 0x1 (that is, the integer 1 in hexadecimal notation)
|
||||
## technically has the type `Num (Integer *)`, so when you pass two of them to
|
||||
## [Num.add], the answer you get is `2 : Num (Integer *)`.
|
||||
##
|
||||
## The type #Float is defined to be an alias for `Num FloatingPoint`, so `3.0 : Num FloatingPoint` is the same answer as `3.0 : Float`. # # Similarly, the number 1 technically has the type `Num Integer`, so when you pass two of them to `Num.add`, the answer you get is `2 : Num Integer`. # # The type #Int is defined to be an alias for `Num Integer`, so `2 : Num Integer` is the same answer as `2 : Int`. #
|
||||
## In this way, the `Num` type makes it possible to have `1 + 1` return `2 : Int` and `1.5 + 1.5` return `3.0 : Float`.
|
||||
## The type [`Frac a`](#Frac) is defined to be an alias for `Num (Fraction a)`,
|
||||
## so `3.0 : Num (Fraction *)` is the same value as `3.0 : Frac *`.
|
||||
## Similarly, the type [`Int a`](#Int) is defined to be an alias for
|
||||
## `Num (Integer a)`, so `2 : Num (Integer *)` is the same value as
|
||||
## `2 : Int *`.
|
||||
##
|
||||
## In this way, the [Num] type makes it possible to have `1 + 0x1` return
|
||||
## `2 : Int *` and `1.5 + 1.5` return `3.0 : Frac`.
|
||||
##
|
||||
## ## Number Literals
|
||||
##
|
||||
|
@ -29,29 +40,30 @@ interface Num2
|
|||
## ends up having the type `Nat`.
|
||||
##
|
||||
## Sometimes number literals don't become more specific. For example,
|
||||
## the #Num.toStr function has the type `Num * -> Str`. This means that
|
||||
## the [Num.toStr] function has the type `Num * -> Str`. This means that
|
||||
## when calling `Num.toStr (5 + 6)`, the expression `(5 + 6)`
|
||||
## still has the type `Num *`. When this happens, `Num *` defaults to
|
||||
## being an #I32 - so this addition expression would overflow
|
||||
## being an [I64] - so this addition expression would overflow
|
||||
## if either 5 or 6 were replaced with a number big enough to cause
|
||||
## addition overflow on an #I32.
|
||||
## addition overflow on an [I64] value.
|
||||
##
|
||||
## If this default of #I32 is not big enough for your purposes,
|
||||
## you can add an `i64` to the end of the number literal, like so:
|
||||
## If this default of [I64] is not big enough for your purposes,
|
||||
## you can add an `i128` to the end of the number literal, like so:
|
||||
##
|
||||
## >>> Num.toStr 5_000_000_000i64
|
||||
## >>> Num.toStr 5_000_000_000i128
|
||||
##
|
||||
## This `i64` suffix specifies that you want this number literal to be
|
||||
## an #I64 instead of a `Num *`. All the other numeric types have
|
||||
## suffixes just like `i64`; here are some other examples:
|
||||
## This `i128` suffix specifies that you want this number literal to be
|
||||
## an [I128] instead of a `Num *`. All the other numeric types have
|
||||
## suffixes just like `i128`; here are some other examples:
|
||||
##
|
||||
## * `215u8` is a `215` value of type #U8
|
||||
## * `76.4f32` is a `76.4` value of type #F32
|
||||
## * `12345ulen` is a `12345` value of type #Nat
|
||||
## * `215u8` is a `215` value of type [U8]
|
||||
## * `76.4f32` is a `76.4` value of type [F32]
|
||||
## * `123.45dec` is a `123.45` value of type [Dec]
|
||||
## * `12345nat` is a `12345` value of type [Nat]
|
||||
##
|
||||
## In practice, these are rarely needed. It's most common to write
|
||||
## number literals without any suffix.
|
||||
Num range : [ @Num range ]
|
||||
Num a : [ @Num a ]
|
||||
|
||||
## A decimal number.
|
||||
##
|
||||
|
@ -110,6 +122,30 @@ Dec : Frac [ @Decimal128 ]
|
|||
## been done in a base-2 floating point calculation, which causes noticeable
|
||||
## precision loss in this case.
|
||||
##
|
||||
## The floating-point numbers ([F32] and [F64]) also have three values which
|
||||
## are not ordinary [finite numbers](https://en.wikipedia.org/wiki/Finite_number).
|
||||
## They are:
|
||||
## * ∞ ([infinity](https://en.wikipedia.org/wiki/Infinity))
|
||||
## * -∞ (negative infinity)
|
||||
## * *NaN* ([not a number](https://en.wikipedia.org/wiki/NaN))
|
||||
##
|
||||
## These values are different from ordinary numbers in that they only occur
|
||||
## when a floating-point calculation encounters an error. For example:
|
||||
## * Dividing a positive [F64] by `0.0` returns ∞.
|
||||
## * Dividing a negative [F64] by `0.0` returns -∞.
|
||||
## * Dividing a [F64] of `0.0` by `0.0` returns [*NaN*](Num.isNaN).
|
||||
##
|
||||
## These rules come from the [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754)
|
||||
## floating point standard. Because almost all modern processors are built to
|
||||
## this standard, deviating from these rules has a significant performance
|
||||
## cost! Since the most common reason to choose [F64] or [F32] over [Dec] is
|
||||
## access to hardware-accelerated performance, Roc follows these rules exactly.
|
||||
##
|
||||
## There's no literal syntax for these error values, but you can check to see if
|
||||
## you ended up with one of them by using [isNaN], [isFinite], and [isInfinite].
|
||||
## Whenever a function in this module could return one of these values, that
|
||||
## possibility is noted in the function's documentation.
|
||||
##
|
||||
## ## Performance Notes
|
||||
##
|
||||
## On typical modern CPUs, performance is similar between [Dec], [F64], and [F32]
|
||||
|
@ -128,7 +164,7 @@ Dec : Frac [ @Decimal128 ]
|
|||
## an even bigger performance difference. [F32] and [F64] can do these in a
|
||||
## single instruction, whereas [Dec] needs entire custom procedures - which use
|
||||
## loops and conditionals. If you need to do performance-critical trigonometry
|
||||
## or square roots, either [F32] or [F64] is probably a better choice than the
|
||||
## or square roots, either [F64] or [F32] is probably a better choice than the
|
||||
## usual default choice of [Dec], despite the precision problems they bring.
|
||||
Frac a : Num [ @Fraction a ]
|
||||
|
||||
|
@ -194,6 +230,17 @@ I64 : Int [ @Signed64 ]
|
|||
U64 : Int [ @Unsigned64 ]
|
||||
I128 : Int [ @Signed128 ]
|
||||
U128 : Int [ @Unsigned128 ]
|
||||
|
||||
## A [natural number](https://en.wikipedia.org/wiki/Natural_number) represented
|
||||
## as a 64-bit unsigned integer on 64-bit systems, a 32-bit unsigned integer
|
||||
## on 32-bit systems, and so on.
|
||||
##
|
||||
## This system-specific size makes it useful for certain data structure
|
||||
## functions like [List.len], because the number of elements many data strucures
|
||||
## can hold is also system-specific. For example, the maximum number of elements
|
||||
## a [List] can hold on a 64-bit system fits in a 64-bit unsigned integer, and
|
||||
## on a 32-bit system it fits in 32-bit unsigned integer. This makes [Nat] a
|
||||
## good fit for [List.len] regardless of system.
|
||||
Nat : Int [ @Natural ]
|
||||
|
||||
## A 64-bit signed integer. All number literals without decimal points are compatible with #Int values.
|
||||
|
@ -272,148 +319,6 @@ Nat : Int [ @Natural ]
|
|||
## If you need to do math outside these bounds, consider using a larger numeric size.
|
||||
Int size : Num [ @Int size ]
|
||||
|
||||
## A 64-bit floating-point number. All number literals with decimal points are #Float values.
|
||||
##
|
||||
## >>> 0.1
|
||||
##
|
||||
## >>> 1.0
|
||||
##
|
||||
## >>> 0.0
|
||||
##
|
||||
## If you like, you can put underscores in your #Float literals.
|
||||
## They have no effect on the number's value, but can make things easier to read.
|
||||
##
|
||||
## >>> 1_000_000.000_000_001
|
||||
##
|
||||
## Roc supports two types of floating-point numbers:
|
||||
##
|
||||
## - *Decimal* floating-point numbers
|
||||
## - *Binary* floating-point numbers
|
||||
##
|
||||
## Decimal floats are precise for decimal calculations. For example:
|
||||
##
|
||||
## >>> 0.1 + 0.2
|
||||
##
|
||||
## Operations on binary floats tend to run *much* faster than operations on
|
||||
## decimal floats, because almost all processors have dedicated instructions
|
||||
## for binary floats and not for decimal floats.
|
||||
## However, binary floats are less precise for decimal calculations.
|
||||
##
|
||||
## For example, here is the same `0.1 + 0.2` calculation again, this time putting
|
||||
## `f64` after the numbers to specify that they should be #F64 binary floats
|
||||
## instead of the default of decimal floats.
|
||||
##
|
||||
## >>> 0.1f64 + 0.2f64
|
||||
##
|
||||
## If decimal precision is unimportant, binary floats give better performance.
|
||||
## If decimal precision is important - for example, when representing money -
|
||||
## decimal floats tend to be worth the performance cost.
|
||||
##
|
||||
## Usually, Roc's compiler can infer a more specific type than #Float for
|
||||
## a particular float value, based on how it is used with other numbers. For example:
|
||||
##
|
||||
## >>> coordinates : { x : F32, y : F32 }
|
||||
## >>> coordinates = { x: 1, y: 2.5 }
|
||||
## >>>
|
||||
## >>> coordinates.x + 1
|
||||
##
|
||||
## On the last line, the compiler infers that the `1` in `+ 1` is an #F32
|
||||
## beacuse it's being added to `coordinates.x`, which was defined to be an #F32
|
||||
## on the first line.
|
||||
##
|
||||
## Sometimes the compiler has no information about which specific type to pick.
|
||||
## For example:
|
||||
##
|
||||
## >>> 0.1 + 0.2 == 0.3
|
||||
##
|
||||
## When this happens, the compiler defaults to choosing #D64 decimal floats.
|
||||
## If you want something else, you can write (for example) `0.1f32 + 0.2 == 0.3`
|
||||
## to compare them as #F32 values instead.
|
||||
##
|
||||
## Both decimal and binary #Float values conform to the [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754#Interchange_formats)
|
||||
## specification for floating point numbers. Conforming to this specification
|
||||
## means Roc's binary floats have nearly universal hardware support, and its
|
||||
## decimal floats have [some hardware support](http://speleotrove.com/decimal/)
|
||||
## among the rare processors which support decimal float instructions at all.
|
||||
##
|
||||
## This specification covers several float formats. Here are the ones Roc supports:
|
||||
##
|
||||
## - #F32 (32-bit binary float)
|
||||
## - #F64 (64-bit binary float)
|
||||
## - #D32 (32-bit decimal float)
|
||||
## - #D64 (64-bit decimal float) # TODO show a table like we do with ints, with the min/max ranges
|
||||
##
|
||||
## Like #Int, it's possible for #Float operations to overflow. Like with ints,
|
||||
## you'll typically get a crash when this happens.
|
||||
##
|
||||
## * In a development build, you'll get an assertion failure.
|
||||
## * In an optimized build, you'll get [`Infinity` or `-Infinity`](https://en.wikipedia.org/wiki/IEEE_754-1985#Positive_and_negative_infinity).
|
||||
##
|
||||
## Although some languages treat have first-class representations for
|
||||
## `-Infinity`, `Infinity`, and the special `NaN` ("not a number")
|
||||
## floating-point values described in the IEEE-754, Roc does not.
|
||||
## Instead, Roc treats all of these as errors. If any Float operation
|
||||
## in a development build encounters one of these values, it will
|
||||
## result in an assertion failure.
|
||||
##
|
||||
## Stll, it's possible that these values may accidentally arise in
|
||||
## release builds. If this happens, they will behave according to the usual
|
||||
## IEEE-754 rules: any operation involving `NaN` will output `NaN`,
|
||||
## any operation involving `Infinity` or `-Infinity` will output either
|
||||
## `Infinity`, `-Infinity`, or `NaN`, and `NaN` is defined to be not
|
||||
## equal to itself - meaning `(x == x)` returns `False` if `x` is `NaN`.
|
||||
##
|
||||
## These are very error-prone values, so if you see an assertion fail in
|
||||
## developent because of one of them, take it seriously - and try to fix
|
||||
## the code so that it can't come up in a release!
|
||||
##
|
||||
## ## Loud versus Quiet errors
|
||||
##
|
||||
## Besides precision problems, another reason floats are error-prone
|
||||
## is that they have quiet error handling built in. For example, in
|
||||
## a 64-bit floating point number, there are certain patterns of those
|
||||
## 64 bits which do not represent valid floats; instead, they represent
|
||||
## invalid results of previous operations.
|
||||
##
|
||||
## Whenever any arithmetic operation is performed on an invalid float,
|
||||
## the result is also invalid. This is called *error propagation*, and
|
||||
## it is notoriously error-prone. In Roc, using equality operations like
|
||||
## `==` and `!=` on an invalid float causes a crash. (See #Float.verify
|
||||
## to check the validity of your float.)
|
||||
##
|
||||
## Beause invalid floats are so error-prone, Roc discourages using them.
|
||||
## Instead, by default it treats them the same way as overflow: by
|
||||
## crashing whenever any #Float function would otherwise return one.
|
||||
## You can also use functions like #Float.tryAdd to get an `Ok` or an error
|
||||
## back so you can gracefully recover from invalid values.
|
||||
##
|
||||
## Quiet errors can be useful sometimes. For example, you might want to
|
||||
## do three floating point calculations in a row, and then gracefully handle
|
||||
## the situation where any one of the three was invalid. In that situation,
|
||||
## quiet errors can be more efficient than using three `try` functions, because
|
||||
## it can have one condition at the end instead of three along the way.
|
||||
##
|
||||
## Another potential use for quiet errors is for risky performance optimizations.
|
||||
## When you are absolutely certain there is no chance of overflow or other
|
||||
## errors, using a *quiet* operation may save an entry in the instruction cache
|
||||
## by removing a branch that would always have been predicted correctly.
|
||||
## Always [measure the performance change](https://youtu.be/r-TLSBdHe1A)
|
||||
## if you do this! The compiler can optimize away those branches behind the scenes,
|
||||
## so you may find that using the quiet version expliitly
|
||||
## makes the code riskier to future change, without actually affecting performance.
|
||||
##
|
||||
## ## Performance Notes
|
||||
##
|
||||
## Currently, loud errors are implemented using an extra conditional. Although
|
||||
## this conditional will always be correctly branh-predicted unless an error
|
||||
## occurs, there is a small effect on the instruction cache, which means
|
||||
## quiet errors are very slightly more efficient.
|
||||
##
|
||||
## Long-term, it's possible that the Roc compiler may be able to implement
|
||||
## loud errors using *signalling errors* in some situations, which could
|
||||
## eliminate the performance difference between loud and quiet errors in
|
||||
## the situation where no error occurs.
|
||||
|
||||
## Convert
|
||||
|
||||
## Return a negative number when given a positive one, and vice versa.
|
||||
|
@ -426,16 +331,16 @@ Int size : Num [ @Int size ]
|
|||
##
|
||||
## >>> Num.neg 0.0
|
||||
##
|
||||
## This is safe to use with any #Float, but it can cause overflow when used with certain #Int values.
|
||||
## This is safe to use with any #Frac, but it can cause overflow when used with certain #Int values.
|
||||
##
|
||||
## For example, calling #Num.neg on the lowest value of a signed integer (such as #Int.lowestI64 or #Int.lowestI32) will cause overflow.
|
||||
## This is because, for any given size of signed integer (32-bit, 64-bit, etc.) its negated lowest value turns out to be 1 higher than
|
||||
## the highest value it can represent. (For this reason, calling #Num.abs on the lowest signed value will also cause overflow.)
|
||||
##
|
||||
## Additionally, calling #Num.neg on any unsigned integer (such as any #U64 or #U32 value) other than 0 will cause overflow.
|
||||
## Additionally, calling #Num.neg on any unsigned integer (such as any #U64 or #U32 value) other than zero will cause overflow.
|
||||
##
|
||||
## (It will never crash when given a #Float, however, because of how floating point numbers represent positive and negative numbers.)
|
||||
neg : Num range -> Num range
|
||||
## (It will never crash when given a #Frac, however, because of how floating point numbers represent positive and negative numbers.)
|
||||
neg : Num a -> Num a
|
||||
|
||||
## Return the absolute value of the number.
|
||||
##
|
||||
|
@ -451,14 +356,14 @@ neg : Num range -> Num range
|
|||
##
|
||||
## >>> Num.abs 0.0
|
||||
##
|
||||
## This is safe to use with any #Float, but it can cause overflow when used with certain #Int values.
|
||||
## This is safe to use with any #Frac, but it can cause overflow when used with certain #Int values.
|
||||
##
|
||||
## For example, calling #Num.abs on the lowest value of a signed integer (such as #Int.lowestI64 or #Int.lowestI32) will cause overflow.
|
||||
## This is because, for any given size of signed integer (32-bit, 64-bit, etc.) its negated lowest value turns out to be 1 higher than
|
||||
## the highest value it can represent. (For this reason, calling #Num.neg on the lowest signed value will also cause overflow.)
|
||||
##
|
||||
## Calling this on an unsigned integer (like #U32 or #U64) never does anything.
|
||||
abs : Num range -> Num range
|
||||
abs : Num a -> Num a
|
||||
|
||||
## Check
|
||||
|
||||
|
@ -485,7 +390,7 @@ isOdd : Num * -> Bool
|
|||
|
||||
## Add two numbers of the same type.
|
||||
##
|
||||
## (To add an #Int and a #Float, first convert one so that they both have the same type. There are functions in the [`Float`](/Float) module that can convert both #Int to #Float and the other way around.)
|
||||
## (To add an #Int and a #Frac, first convert one so that they both have the same type. There are functions in the [`Frac`](/Frac) module that can convert both #Int to #Frac and the other way around.)
|
||||
##
|
||||
## `a + b` is shorthand for `Num.add a b`.
|
||||
##
|
||||
|
@ -495,13 +400,24 @@ isOdd : Num * -> Bool
|
|||
##
|
||||
## `Num.add` can be convenient in pipelines.
|
||||
##
|
||||
## >>> Float.pi
|
||||
## >>> Frac.pi
|
||||
## >>> |> Num.add 1.0
|
||||
add : Num range, Num range -> Num range
|
||||
##
|
||||
## If the answer to this operation can't fit in the return value (e.g. an
|
||||
## [I8] answer that's higher than 127 or lower than -128), the result is an
|
||||
## *overflow*. For [F64] and [F32], overflow results in an answer of either
|
||||
## ∞ or -∞. For all other number types, overflow results in a panic.
|
||||
add : Num a, Num a -> Num a
|
||||
|
||||
## Add two numbers and check for overflow.
|
||||
##
|
||||
## This is the same as [Num.add] except if the operation overflows, instead of
|
||||
## panicking or returning ∞ or -∞, it will return `Err Overflow`.
|
||||
addCheckOverflow : Num a, Num a -> Result (Num a) [ Overflow ]*
|
||||
|
||||
## Subtract two numbers of the same type.
|
||||
##
|
||||
## (To subtract an #Int and a #Float, first convert one so that they both have the same type. There are functions in the [`Float`](/Float) module that can convert both #Int to #Float and the other way around.)
|
||||
## (To subtract an #Int and a #Frac, first convert one so that they both have the same type. There are functions in the [`Frac`](/Frac) module that can convert both #Int to #Frac and the other way around.)
|
||||
##
|
||||
## `a - b` is shorthand for `Num.sub a b`.
|
||||
##
|
||||
|
@ -511,13 +427,24 @@ add : Num range, Num range -> Num range
|
|||
##
|
||||
## `Num.sub` can be convenient in pipelines.
|
||||
##
|
||||
## >>> Float.pi
|
||||
## >>> Frac.pi
|
||||
## >>> |> Num.sub 2.0
|
||||
sub : Num range, Num range -> Num range
|
||||
##
|
||||
## If the answer to this operation can't fit in the return value (e.g. an
|
||||
## [I8] answer that's higher than 127 or lower than -128), the result is an
|
||||
## *overflow*. For [F64] and [F32], overflow results in an answer of either
|
||||
## ∞ or -∞. For all other number types, overflow results in a panic.
|
||||
sub : Num a, Num a -> Num a
|
||||
|
||||
## Subtract two numbers and check for overflow.
|
||||
##
|
||||
## This is the same as [Num.sub] except if the operation overflows, instead of
|
||||
## panicking or returning ∞ or -∞, it will return `Err Overflow`.
|
||||
subCheckOverflow : Num a, Num a -> Result (Num a) [ Overflow ]*
|
||||
|
||||
## Multiply two numbers of the same type.
|
||||
##
|
||||
## (To multiply an #Int and a #Float, first convert one so that they both have the same type. There are functions in the [`Float`](/Float) module that can convert both #Int to #Float and the other way around.)
|
||||
## (To multiply an #Int and a #Frac, first convert one so that they both have the same type. There are functions in the [`Frac`](/Frac) module that can convert both #Int to #Frac and the other way around.)
|
||||
##
|
||||
## `a * b` is shorthand for `Num.mul a b`.
|
||||
##
|
||||
|
@ -527,9 +454,20 @@ sub : Num range, Num range -> Num range
|
|||
##
|
||||
## `Num.mul` can be convenient in pipelines.
|
||||
##
|
||||
## >>> Float.pi
|
||||
## >>> Frac.pi
|
||||
## >>> |> Num.mul 2.0
|
||||
mul : Num range, Num range -> Num range
|
||||
##
|
||||
## If the answer to this operation can't fit in the return value (e.g. an
|
||||
## [I8] answer that's higher than 127 or lower than -128), the result is an
|
||||
## *overflow*. For [F64] and [F32], overflow results in an answer of either
|
||||
## ∞ or -∞. For all other number types, overflow results in a panic.
|
||||
mul : Num a, Num a -> Num a
|
||||
|
||||
## Multiply two numbers and check for overflow.
|
||||
##
|
||||
## This is the same as [Num.mul] except if the operation overflows, instead of
|
||||
## panicking or returning ∞ or -∞, it will return `Err Overflow`.
|
||||
mulCheckOverflow : Num a, Num a -> Result (Num a) [ Overflow ]*
|
||||
|
||||
## Convert
|
||||
|
||||
|
@ -540,13 +478,16 @@ mul : Num range, Num range -> Num range
|
|||
##
|
||||
## >>> Num.toStr 42
|
||||
##
|
||||
## Only #Float values will include a decimal point, and they will always include one.
|
||||
## Only #Frac values will include a decimal point, and they will always include one.
|
||||
##
|
||||
## >>> Num.toStr 4.2
|
||||
##
|
||||
## >>> Num.toStr 4.0
|
||||
##
|
||||
## For other bases see #toHexStr, #toOctalStr, and #toBinaryStr.
|
||||
## When this function is given a non-[finite](Num.isFinite)
|
||||
## [F64] or [F32] value, the returned string will be `"NaN"`, `"∞"`, or `"-∞"`.
|
||||
##
|
||||
## To get strings in hexadecimal, octal, or binary format, use [Num.format].
|
||||
toStr : Num * -> Str
|
||||
|
||||
## Convert a number into a [Str], formatted with the given options.
|
||||
|
@ -612,10 +553,10 @@ format :
|
|||
-> Str
|
||||
|
||||
## Round off the given float to the nearest integer.
|
||||
round : Float * -> Int *
|
||||
ceil : Float * -> Int *
|
||||
floor : Float * -> Int *
|
||||
trunc : Float * -> Int *
|
||||
round : Frac * -> Int *
|
||||
ceil : Frac * -> Int *
|
||||
floor : Frac * -> Int *
|
||||
trunc : Frac * -> Int *
|
||||
|
||||
## Convert an #Int to a #Nat. If the given number doesn't fit in #Nat, it will be truncated.
|
||||
## Since #Nat has a different maximum number depending on the system you're building
|
||||
|
@ -630,13 +571,13 @@ trunc : Float * -> Int *
|
|||
## the #Nat value of 9_000_000_000. This is because on a 64-bit system, #Nat can
|
||||
## hold up to #Num.maxU64, and 9_000_000_000 is lower than #Num.maxU64.
|
||||
##
|
||||
## To convert a #Float to a #Nat, first call either #Num.round, #Num.ceil, or #Num.floor
|
||||
## To convert a #Frac to a #Nat, first call either #Num.round, #Num.ceil, or #Num.floor
|
||||
## on it, then call this on the resulting #Int.
|
||||
toNat : Int * -> Nat
|
||||
|
||||
## Convert an #Int to an #I8. If the given number doesn't fit in #I8, it will be truncated.
|
||||
##
|
||||
## To convert a #Float to an #I8, first call either #Num.round, #Num.ceil, or #Num.floor
|
||||
## To convert a #Frac to an #I8, first call either #Num.round, #Num.ceil, or #Num.floor
|
||||
## on it, then call this on the resulting #Int.
|
||||
toI8 : Int * -> I8
|
||||
toI16 : Int * -> I16
|
||||
|
@ -660,13 +601,9 @@ toF32 : Num * -> F32
|
|||
## there will be a loss of precision.
|
||||
toF64 : Num * -> F64
|
||||
|
||||
## Convert a #Num to a #D32. If the given number can't be precisely represented in a #D32,
|
||||
## Convert a #Num to a #Dec. If the given number can't be precisely represented in a #Dec,
|
||||
## there will be a loss of precision.
|
||||
toD32 : Num * -> D32
|
||||
|
||||
## Convert a #Num to a #D64. If the given number can't be precisely represented in a #D64,
|
||||
## there will be a loss of precision.
|
||||
toD64 : Num * -> D64
|
||||
toDec : Num * -> Dec
|
||||
|
||||
## Divide two integers and #Num.round the resulut.
|
||||
##
|
||||
|
@ -689,16 +626,16 @@ toD64 : Num * -> D64
|
|||
## >>> Num.divRound 8 -3
|
||||
##
|
||||
## This is the same as the #// operator.
|
||||
divRound : Int, Int -> Int
|
||||
divRound : Int a, Int a -> Int a
|
||||
|
||||
## Perform flooring modulo on two integers.
|
||||
##
|
||||
## Modulo is the same as remainder when working with positive numbers,
|
||||
## but if either number is negative, then modulo works differently.
|
||||
##
|
||||
## Additionally, flooring modulo uses #Float.floor on the result.
|
||||
## Additionally, flooring modulo uses #Frac.floor on the result.
|
||||
##
|
||||
## (Use #Float.mod for non-flooring modulo.)
|
||||
## (Use #Frac.mod for non-flooring modulo.)
|
||||
##
|
||||
## Return `Err DivByZero` if the second integer is zero, because division by zero is undefined in mathematics.
|
||||
##
|
||||
|
@ -711,40 +648,16 @@ divRound : Int, Int -> Int
|
|||
## >>> -8 %% -3
|
||||
##
|
||||
## >>> Int.modFloor -8 -3
|
||||
#modFloor : Int, Int -> Result DivByZero Int
|
||||
#modFloor : Int a, Int a -> Result (Int a) [ DivByZero ]*
|
||||
|
||||
|
||||
## Bitwise
|
||||
|
||||
xor : Int, Int -> Int
|
||||
xor : Int a, Int a -> Int a
|
||||
|
||||
and : Int, Int -> Int
|
||||
and : Int a, Int a -> Int a
|
||||
|
||||
not : Int -> Int
|
||||
|
||||
## Sort ascending - that is, with the lowest first, and the highest last.
|
||||
##
|
||||
## List.sort Num.asc [ 3, 6, 0 ]
|
||||
##
|
||||
asc : Num a, Num a -> [ Eq, Lt, Gt ]
|
||||
|
||||
## Sort descending - that is, with the highest first, and the lowest last.
|
||||
##
|
||||
## List.sort Num.desc [ 3, 6, 0 ]
|
||||
##
|
||||
desc : Num a, Num a -> [ Eq, Lt, Gt ]
|
||||
|
||||
## TODO should we offer hash32 etc even if someday it has to do a hash64 and truncate?
|
||||
##
|
||||
## This function can crash under these circumstances:
|
||||
##
|
||||
## * It receives a function, or any type that contains a function (for example a record, tag, or #List containing a function)
|
||||
## * It receives an erroneous #Float (`NaN`, `Infinity`, or `-Infinity` - these values can only originate from hosts)
|
||||
##
|
||||
## CAUTION: This function may give different answers in future releases of Roc,
|
||||
## so be aware that if you rely on the exact answer this gives today, your
|
||||
## code may break in a future Roc release.
|
||||
hash64 : a -> U64
|
||||
not : Int a -> Int a
|
||||
|
||||
## Limits
|
||||
|
||||
|
@ -803,88 +716,81 @@ maxU32 : U32
|
|||
## and zero is the lowest unsigned number. Unsigned numbers cannot be negative.
|
||||
minU32 : U32
|
||||
|
||||
## The highest supported #Float value you can have, which is approximately 1.8 × 10^308.
|
||||
## The highest supported #F64 value you can have, which is approximately 1.8 × 10^308.
|
||||
##
|
||||
## If you go higher than this, your running Roc code will crash - so be careful not to!
|
||||
maxF64 : Float *
|
||||
maxF64 : F64
|
||||
|
||||
## The lowest supported #Float value you can have, which is approximately -1.8 × 10^308.
|
||||
## The lowest supported #F64 value you can have, which is approximately -1.8 × 10^308.
|
||||
##
|
||||
## If you go lower than this, your running Roc code will crash - so be careful not to!
|
||||
minF64 : Float *
|
||||
minF64 : F64
|
||||
|
||||
## The highest integer that can be represented as a #Float without # losing precision.
|
||||
## It is equal to 2^53, which is approximately 9 × 10^15.
|
||||
## The highest supported #F32 value you can have, which is approximately 1.8 × 10^308.
|
||||
##
|
||||
## Some integers higher than this can be represented, but they may lose precision. For example:
|
||||
##
|
||||
## >>> Float.highestInt
|
||||
##
|
||||
## >>> Float.highestInt + 100 # Increasing may lose precision
|
||||
##
|
||||
## >>> Float.highestInt - 100 # Decreasing is fine - but watch out for lowestLosslessInt!
|
||||
maxPreciseInt : Float *
|
||||
## If you go higher than this, your running Roc code will crash - so be careful not to!
|
||||
maxF32 : F32
|
||||
|
||||
## The lowest integer that can be represented as a #Float without losing precision.
|
||||
## It is equal to -2^53, which is approximately -9 × 10^15.
|
||||
## The lowest supported #F32 value you can have, which is approximately -1.8 × 10^308.
|
||||
##
|
||||
## Some integers lower than this can be represented, but they may lose precision. For example:
|
||||
## If you go lower than this, your running Roc code will crash - so be careful not to!
|
||||
minF32 : F32
|
||||
|
||||
## The highest supported #F64 value you can have, which is approximately 1.8 × 10^308.
|
||||
##
|
||||
## >>> Float.lowestIntVal
|
||||
## If you go higher than this, your running Roc code will crash - so be careful not to!
|
||||
maxDec : Dec
|
||||
|
||||
## The lowest supported #F64 value you can have, which is approximately -1.8 × 10^308.
|
||||
##
|
||||
## >>> Float.lowestIntVal - 100 # Decreasing may lose precision
|
||||
##
|
||||
## >>> Float.lowestIntVal + 100 # Increasing is fine - but watch out for highestInt!
|
||||
maxPreciseInt : Float *
|
||||
## If you go lower than this, your running Roc code will crash - so be careful not to!
|
||||
maxDec : Dec
|
||||
|
||||
## Constants
|
||||
|
||||
## An approximation of e, specifically 2.718281828459045.
|
||||
e : Float *
|
||||
e : Frac *
|
||||
|
||||
## An approximation of pi, specifically 3.141592653589793.
|
||||
pi : Float *
|
||||
## Constants
|
||||
|
||||
## An approximation of e, specifically 2.718281828459045.
|
||||
e : Float *
|
||||
|
||||
## An approximation of pi, specifically 3.141592653589793.
|
||||
pi : Float *
|
||||
|
||||
#ceiling : Float -> Int
|
||||
|
||||
#floor : Float -> Int
|
||||
pi : Frac *
|
||||
|
||||
## Trigonometry
|
||||
|
||||
#cos : Float -> Float
|
||||
cos : Frac a -> Frac a
|
||||
|
||||
#acos : Float -> Float
|
||||
acos : Frac a -> Frac a
|
||||
|
||||
#sin : Float -> Float
|
||||
sin : Frac a -> Frac a
|
||||
|
||||
#asin : Float -> Float
|
||||
asin : Frac a -> Frac a
|
||||
|
||||
#tan : Float -> Float
|
||||
tan : Frac a -> Frac a
|
||||
|
||||
#atan : Float -> Float
|
||||
atan : Frac a -> Frac a
|
||||
|
||||
## Other Calculations (arithmetic?)
|
||||
|
||||
## Divide two #Float numbers.
|
||||
## Divide one [Frac] by another.
|
||||
##
|
||||
## `a / b` is shorthand for `Num.div a b`.
|
||||
##
|
||||
## Division by zero is undefined in mathematics. As such, you should make
|
||||
## sure never to pass zero as the denomaintor to this function!
|
||||
## [Division by zero is undefined in mathematics](https://en.wikipedia.org/wiki/Division_by_zero).
|
||||
## As such, you should make sure never to pass zero as the denomaintor to this function!
|
||||
## Calling [div] on a [Dec] denominator of zero will cause a panic.
|
||||
##
|
||||
## If zero does get passed as the denominator...
|
||||
## Calling [div] on [F32] and [F64] values follows these rules:
|
||||
## * Dividing a positive [F64] or [F32] by zero returns ∞.
|
||||
## * Dividing a negative [F64] or [F32] by zero returns -∞.
|
||||
## * Dividing a zero [F64] or [F32] by zero returns [*NaN*](Num.isNaN).
|
||||
##
|
||||
## * In a development build, you'll get an assertion failure.
|
||||
## * In a release build, the function will return `Infinity`, `-Infinity`, or `NaN` depending on the arguments.
|
||||
## > These rules come from the [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754)
|
||||
## > floating point standard. Because almost all modern processors are built to
|
||||
## > this standard, deviating from these rules has a significant performance
|
||||
## > cost! Since the most common reason to choose [F64] or [F32] over [Dec] is
|
||||
## > access to hardware-accelerated performance, Roc follows these rules exactly.
|
||||
##
|
||||
## To divide an #Int and a #Float, first convert the #Int to a #Float using one of the functions in this module.
|
||||
## To divide an [Int] and a [Frac], first convert the [Int] to a [Frac] using
|
||||
## one of the functions in this module like [toDec].
|
||||
##
|
||||
## >>> 5.0 / 7.0
|
||||
##
|
||||
|
@ -892,45 +798,47 @@ pi : Float *
|
|||
##
|
||||
## `Num.div` can be convenient in pipelines.
|
||||
##
|
||||
## >>> Float.pi
|
||||
## >>> Num.pi
|
||||
## >>> |> Num.div 2.0
|
||||
#div : Float, Float -> Result Float DivByZero
|
||||
div = \numerator, denominator ->
|
||||
when numerator is
|
||||
0.0 -> 0.0 # TODO return Result!
|
||||
_ -> denominator
|
||||
div : Frac a, Frac a -> Frac a
|
||||
|
||||
## Perform modulo on two #Float numbers.
|
||||
## Perform modulo on two [Frac]s.
|
||||
##
|
||||
## Modulo is the same as remainder when working with positive numbers,
|
||||
## but if either number is negative, then modulo works differently.
|
||||
##
|
||||
## Return `Err DivByZero` if the second number is zero, because division by zero is undefined in mathematics.
|
||||
## `a % b` is shorthand for `Num.mod a b`.
|
||||
##
|
||||
## `a % b` is shorthand for `Float.mod a b`.
|
||||
## [Division by zero is undefined in mathematics](https://en.wikipedia.org/wiki/Division_by_zero),
|
||||
## and as such, so is modulo by zero. Because of this, you should make sure never
|
||||
## to pass zero for the second argument to this function!
|
||||
##
|
||||
## Passing [mod] a [Dec] value of zero for its second argument will cause a panic.
|
||||
## Passing [mod] a [F32] and [F64] value for its second argument will cause it
|
||||
## to return [*NaN*](Num.isNaN).
|
||||
##
|
||||
## >>> 5.0 % 7.0
|
||||
##
|
||||
## >>> Float.mod 5 7
|
||||
## >>> Num.mod 5 7
|
||||
##
|
||||
## `Float.mod` can be convenient in pipelines.
|
||||
## `Num.mod` can be convenient in pipelines.
|
||||
##
|
||||
## >>> Float.pi
|
||||
## >>> |> Float.mod 2.0
|
||||
mod : Float a, Float a -> Result (Float a) [ DivByZero ]*
|
||||
## >>> Num.pi
|
||||
## >>> |> Num.mod 2.0
|
||||
mod : Frac a, Frac a -> Frac a
|
||||
|
||||
## Raises a #Float to the power of another #Float.
|
||||
## Raises a #Frac to the power of another #Frac.
|
||||
##
|
||||
## `
|
||||
## For an #Int alternative to this function, see #Num.raise.
|
||||
pow : Float a, Float a -> Float a
|
||||
pow : Frac a, Frac a -> Frac a
|
||||
|
||||
## Raises an integer to the power of another, by multiplying the integer by
|
||||
## itself the given number of times.
|
||||
##
|
||||
## This process is known as [exponentiation by squaring](https://en.wikipedia.org/wiki/Exponentiation_by_squaring).
|
||||
##
|
||||
## For a #Float alternative to this function, which supports negative exponents,
|
||||
## For a #Frac alternative to this function, which supports negative exponents,
|
||||
## see #Num.exp.
|
||||
##
|
||||
## >>> Num.exp 5 0
|
||||
|
@ -947,33 +855,176 @@ pow : Float a, Float a -> Float a
|
|||
## overflow
|
||||
expBySquaring : Int a, U8 -> Int a
|
||||
|
||||
## Return the reciprocal of a #Float - that is, divides `1.0` by the given number.
|
||||
## Returns an approximation of the absolute value of a [Frac]'s square root.
|
||||
##
|
||||
## Crashes if given `0.0`, because division by zero is undefined in mathematics.
|
||||
## The square root of a negative number is an irrational number, and [Frac] only
|
||||
## supports rational numbers. As such, you should make sure never to pass this
|
||||
## function a negative number! Calling [sqrt] on a negative [Dec] will cause a panic.
|
||||
##
|
||||
## For a version that does not crash, use #tryRecip
|
||||
recip : Float a -> Result (Float a) [ DivByZero ]*
|
||||
## Calling [sqrt] on [F32] and [F64] values follows these rules:
|
||||
## * Passing a negative [F64] or [F32] returns [*NaN*](Num.isNaN).
|
||||
## * Passing [*NaN*](Num.isNaN) or -∞ also returns [*NaN*](Num.isNaN).
|
||||
## * Passing ∞ returns ∞.
|
||||
##
|
||||
## > These rules come from the [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754)
|
||||
## > floating point standard. Because almost all modern processors are built to
|
||||
## > this standard, deviating from these rules has a significant performance
|
||||
## > cost! Since the most common reason to choose [F64] or [F32] over [Dec] is
|
||||
## > access to hardware-accelerated performance, Roc follows these rules exactly.
|
||||
##
|
||||
## >>> Frac.sqrt 4.0
|
||||
##
|
||||
## >>> Frac.sqrt 1.5
|
||||
##
|
||||
## >>> Frac.sqrt 0.0
|
||||
##
|
||||
## >>> Frac.sqrt -4.0f64
|
||||
##
|
||||
## >>> Frac.sqrt -4.0dec
|
||||
sqrt : Frac a -> Frac a
|
||||
|
||||
## NOTE: Need to come up a suffix alternative to the "try" prefix.
|
||||
## This should be like (for example) recipTry so that it's more discoverable
|
||||
## in documentation and editor autocomplete when you type "recip"
|
||||
tryRecip : Float a -> Result (Float a) [ DivByZero ]*
|
||||
## Bit shifts
|
||||
|
||||
## Return an approximation of the absolute value of the square root of the #Float.
|
||||
## [Logical bit shift](https://en.wikipedia.org/wiki/Bitwise_operation#Logical_shift) left.
|
||||
##
|
||||
## Return #InvalidSqrt if given a negative number or an invalid #Float. The square root of a negative number is an irrational number, and #Float only supports rational numbers.
|
||||
## `a << b` is shorthand for `Num.shl a b`.
|
||||
shl : Int a, Int a -> Int a
|
||||
|
||||
## [Arithmetic bit shift](https://en.wikipedia.org/wiki/Bitwise_operation#Arithmetic_shift) left.
|
||||
##
|
||||
## >>> Float.sqrt 4.0
|
||||
## This is called `shlWrap` because any bits shifted
|
||||
## off the beginning of the number will be wrapped around to
|
||||
## the end. (In contrast, [shl] replaces discarded bits with zeroes.)
|
||||
shlWrap : Int a, Int a -> Int a
|
||||
|
||||
## [Logical bit shift](https://en.wikipedia.org/wiki/Bitwise_operation#Logical_shift) right.
|
||||
##
|
||||
## >>> Float.sqrt 1.5
|
||||
## `a >> b` is shorthand for `Num.shr a b`.
|
||||
shr : Int a, Int a -> Int a
|
||||
|
||||
## [Arithmetic bit shift](https://en.wikipedia.org/wiki/Bitwise_operation#Arithmetic_shift) right.
|
||||
##
|
||||
## >>> Float.sqrt 0.0
|
||||
##
|
||||
## >>> Float.sqrt -4.0
|
||||
sqrt : Float a -> [Ok (Float a), InvalidSqrt]*
|
||||
## This is called `shlWrap` because any bits shifted
|
||||
## off the end of the number will be wrapped around to
|
||||
## the beginning. (In contrast, [shr] replaces discarded bits with zeroes.)
|
||||
shrWrap : Int a, Int a -> Int a
|
||||
|
||||
|
||||
## [Endianness](https://en.wikipedia.org/wiki/Endianness)
|
||||
Endi : [ Big, Little ]
|
||||
|
||||
toBytes : Num *, Endi -> List U8
|
||||
|
||||
|
||||
## Comparison
|
||||
|
||||
## Returns `True` if the first number is less than the second.
|
||||
##
|
||||
## `a < b` is shorthand for `Num.isLt a b`.
|
||||
##
|
||||
## If either argument is [*NaN*](Num.isNaN), returns `False` no matter what. (*NaN*
|
||||
## is [defined to be unordered](https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN).)
|
||||
##
|
||||
## >>> 5
|
||||
## >>> |> Num.isLt 6
|
||||
isLt : Num a, Num a -> Bool
|
||||
|
||||
## Returns `True` if the first number is less than or equal to the second.
|
||||
##
|
||||
## `a <= b` is shorthand for `Num.isLte a b`.
|
||||
##
|
||||
## If either argument is [*NaN*](Num.isNaN), returns `False` no matter what. (*NaN*
|
||||
## is [defined to be unordered](https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN).)
|
||||
isLte : Num a, Num a -> Bool
|
||||
|
||||
## Returns `True` if the first number is greater than the second.
|
||||
##
|
||||
## `a > b` is shorthand for `Num.isGt a b`.
|
||||
##
|
||||
## If either argument is [*NaN*](Num.isNaN), returns `False` no matter what. (*NaN*
|
||||
## is [defined to be unordered](https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN).)
|
||||
##
|
||||
## >>> 6
|
||||
## >>> |> Num.isGt 5
|
||||
isGt : Num a, Num a -> Bool
|
||||
|
||||
## Returns `True` if the first number is greater than or equal to the second.
|
||||
##
|
||||
## `a >= b` is shorthand for `Num.isGte a b`.
|
||||
##
|
||||
## If either argument is [*NaN*](Num.isNaN), returns `False` no matter what. (*NaN*
|
||||
## is [defined to be unordered](https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN).)
|
||||
isGte : Num a, Num a -> Bool
|
||||
|
||||
## Returns the higher of two numbers.
|
||||
##
|
||||
## If either argument is [*NaN*](Num.isNaN), returns `False` no matter what. (*NaN*
|
||||
## is [defined to be unordered](https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN).)
|
||||
higher : Num a, Num a -> Num a
|
||||
|
||||
## Returns the lower of two numbers.
|
||||
##
|
||||
## If either argument is [*NaN*](Num.isNaN), returns `False` no matter what. (*NaN*
|
||||
## is [defined to be unordered](https://en.wikipedia.org/wiki/NaN#Comparison_with_NaN).)
|
||||
lower : Num a, Num a -> Num a
|
||||
|
||||
# Branchless implementation that works for all numeric types:
|
||||
#
|
||||
# let is_lt = arg1 < arg2;
|
||||
# let is_eq = arg1 == arg2;
|
||||
# return (is_lt as i8 - is_eq as i8) + 1;
|
||||
#
|
||||
# 1, 1 -> (0 - 1) + 1 == 0 # Eq
|
||||
# 5, 1 -> (0 - 0) + 1 == 1 # Gt
|
||||
# 1, 5 -> (1 - 0) + 1 == 2 # Lt
|
||||
|
||||
## Returns `Lt` if the first number is less than the second, `Gt` if
|
||||
## the first is greater than the second, and `Eq` if they're equal.
|
||||
##
|
||||
## Although this can be passed to [List.sort], you'll get better performance
|
||||
## by using [List.sortAsc] or [List.sortDesc] instead.
|
||||
compare : Num a, Num a -> [ Lt, Eq, Gt ]
|
||||
|
||||
## Special Floating-Point Values
|
||||
|
||||
## When given a [F64] or [F32] value, returns `False` if that value is
|
||||
## [*NaN*](Num.isNaN), ∞ or -∞, and `True` otherwise.
|
||||
##
|
||||
## Always returns `True` when given a [Dec].
|
||||
##
|
||||
## This is the opposite of [isInfinite], except when given [*NaN*](Num.isNaN). Both
|
||||
## [isFinite] and [isInfinite] return `False` for [*NaN*](Num.isNaN).
|
||||
isFinite : Frac * -> Bool
|
||||
|
||||
## When given a [F64] or [F32] value, returns `True` if that value is either
|
||||
## ∞ or -∞, and `False` otherwise.
|
||||
##
|
||||
## Always returns `False` when given a [Dec].
|
||||
##
|
||||
## This is the opposite of [isFinite], except when given [*NaN*](Num.isNaN). Both
|
||||
## [isFinite] and [isInfinite] return `False` for [*NaN*](Num.isNaN).
|
||||
isInfinite : Frac * -> Bool
|
||||
|
||||
## When given a [F64] or [F32] value, returns `True` if that value is
|
||||
## *NaN* ([not a number](https://en.wikipedia.org/wiki/NaN)), and `False` otherwise.
|
||||
##
|
||||
## Always returns `False` when given a [Dec].
|
||||
##
|
||||
## >>> Num.isNaN 12.3
|
||||
##
|
||||
## >>> Num.isNaN (Num.sqrt -2)
|
||||
##
|
||||
## *NaN* is unusual from other numberic values in that:
|
||||
## * *NaN* is not equal to any other number, even itself. [Bool.isEq] always returns `False` if either argument is *NaN*.
|
||||
## * *NaN* has no ordering, so [isLt], [isLte], [isGt], and [isGte] always return `False` if either argument is *NaN*.
|
||||
##
|
||||
## These rules come from the [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754)
|
||||
## floating point standard. Because almost all modern processors are built to
|
||||
## this standard, deviating from these rules has a significant performance
|
||||
## cost! Since the most common reason to choose [F64] or [F32] over [Dec] is
|
||||
## access to hardware-accelerated performance, Roc follows these rules exactly.
|
||||
##
|
||||
## Note that you should never put a *NaN* into a [Set], or use it as the key in
|
||||
## a [Dict]. The result is entries that can never be removed from those
|
||||
## collections! See the documentation for [Set.add] and [Dict.insert] for details.
|
||||
isNaN : Frac * -> Bool
|
||||
|
|
|
@ -18,6 +18,9 @@ len : Set * -> Nat
|
|||
|
||||
# TODO: removed `'` from signature because parser does not support it yet
|
||||
# Original signature: `add : Set 'elem, 'elem -> Set 'elem`
|
||||
## Make sure never to add a *NaN* to a [Set]! Becuase *NaN* is defined to be
|
||||
## unequal to *NaN*, adding a *NaN* results in an entry that can never be
|
||||
## retrieved or removed from the [Set].
|
||||
add : Set elem, elem -> Set elem
|
||||
|
||||
## Drops the given element from the set.
|
||||
|
|
|
@ -456,10 +456,17 @@ parseU64 : Str, NumParseConfig -> Result { val : U64, rest : Str } [ Expected [
|
|||
parseI64 : Str, NumParseConfig -> Result { val : I64, rest : Str } [ Expected [ NumI64 ]* Str ]*
|
||||
parseU128 : Str, NumParseConfig -> Result { val : U128, rest : Str } [ Expected [ NumU128 ]* Str ]*
|
||||
parseI128 : Str, NumParseConfig -> Result { val : I128, rest : Str } [ Expected [ NumI128 ]* Str ]*
|
||||
parseF64 : Str, NumParseConfig -> Result { val : U128, rest : Str } [ Expected [ NumF64 ]* Str ]*
|
||||
parseF32 : Str, NumParseConfig -> Result { val : I128, rest : Str } [ Expected [ NumF32 ]* Str ]*
|
||||
parseDec : Str, NumParseConfig -> Result { val : Dec, rest : Str } [ Expected [ NumDec ]* Str ]*
|
||||
|
||||
## If the string begins with a [finite](Num.isFinite) [F64] number, return
|
||||
## that number along with the rest of the string after it.
|
||||
##
|
||||
## If the string begins with `"NaN"`, `"∞"`, and `"-∞"` (which do not represent
|
||||
## [finite](Num.isFinite) numbers), they will be similarly accepted and
|
||||
## translated into their respective [F64] values.
|
||||
parseF64 : Str, NumParseConfig -> Result { val : F64, rest : Str } [ Expected [ NumF64 ]* Str ]*
|
||||
parseF32 : Str, NumParseConfig -> Result { val : F32, rest : Str } [ Expected [ NumF32 ]* Str ]*
|
||||
|
||||
## Notes:
|
||||
## * You can allow a decimal mark for integers; they'll only parse if the numbers after it are all 0.
|
||||
## * For `wholeSep`, `Required` has a payload for how many digits (e.g. "required every 3 digits")
|
||||
|
@ -475,4 +482,3 @@ NumParseConfig :
|
|||
trailingZeroes ? [ Allowed, Disallowed ],
|
||||
wholeSep ? { mark : Str, policy : [ Allowed, Required U64 ] }
|
||||
}
|
||||
-> Str
|
||||
|
|
|
@ -3,12 +3,6 @@ pub const OBJ_PATH: &str = env!(
|
|||
"Env var BUILTINS_O not found. Is there a problem with the build script?"
|
||||
);
|
||||
|
||||
pub fn as_bytes() -> &'static [u8] {
|
||||
// In the build script for the builtins module,
|
||||
// we compile the builtins into LLVM bitcode
|
||||
include_bytes!("../bitcode/builtins.bc")
|
||||
}
|
||||
|
||||
pub const NUM_ASIN: &str = "roc_builtins.num.asin";
|
||||
pub const NUM_ACOS: &str = "roc_builtins.num.acos";
|
||||
pub const NUM_ATAN: &str = "roc_builtins.num.atan";
|
||||
|
|
|
@ -292,7 +292,7 @@ pub fn types() -> MutMap<Symbol, (SolvedType, Region)> {
|
|||
// minInt : Int range
|
||||
add_type!(Symbol::NUM_MIN_INT, int_type(flex(TVAR1)));
|
||||
|
||||
// div : Int, Int -> Result Int [ DivByZero ]*
|
||||
// divInt : Int a, Int a -> Result (Int a) [ DivByZero ]*
|
||||
let div_by_zero = SolvedType::TagUnion(
|
||||
vec![(TagName::Global("DivByZero".into()), vec![])],
|
||||
Box::new(SolvedType::Wildcard),
|
||||
|
|
|
@ -30,7 +30,7 @@ macro_rules! macro_magic {
|
|||
/// Some builtins cannot be constructed in code gen alone, and need to be defined
|
||||
/// as separate Roc defs. For example, List.get has this type:
|
||||
///
|
||||
/// List.get : List elem, Int -> Result elem [ OutOfBounds ]*
|
||||
/// List.get : List elem, Nat -> Result elem [ OutOfBounds ]*
|
||||
///
|
||||
/// Because this returns an open tag union for its Err type, it's not possible
|
||||
/// for code gen to return a hardcoded value for OutOfBounds. For example,
|
||||
|
@ -450,7 +450,7 @@ fn num_add(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
|||
num_binop(symbol, var_store, LowLevel::NumAdd)
|
||||
}
|
||||
|
||||
/// Num.addWrap : Int, Int -> Int
|
||||
/// Num.addWrap : Int a, Int a -> Int a
|
||||
fn num_add_wrap(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
num_binop(symbol, var_store, LowLevel::NumAddWrap)
|
||||
}
|
||||
|
@ -549,7 +549,7 @@ fn num_sub(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
|||
num_binop(symbol, var_store, LowLevel::NumSub)
|
||||
}
|
||||
|
||||
/// Num.subWrap : Int, Int -> Int
|
||||
/// Num.subWrap : Int a, Int a -> Int a
|
||||
fn num_sub_wrap(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
num_binop(symbol, var_store, LowLevel::NumSubWrap)
|
||||
}
|
||||
|
@ -648,7 +648,7 @@ fn num_mul(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
|||
num_binop(symbol, var_store, LowLevel::NumMul)
|
||||
}
|
||||
|
||||
/// Num.mulWrap : Int, Int -> Int
|
||||
/// Num.mulWrap : Int a, Int a -> Int a
|
||||
fn num_mul_wrap(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
num_binop(symbol, var_store, LowLevel::NumMulWrap)
|
||||
}
|
||||
|
@ -1152,7 +1152,7 @@ fn num_ceiling(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
|||
)
|
||||
}
|
||||
|
||||
/// Num.powInt : Int, Int -> Int
|
||||
/// Num.powInt : Int a, Int a -> Int a
|
||||
fn num_pow_int(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
let int_var = var_store.fresh();
|
||||
|
||||
|
@ -1251,17 +1251,17 @@ fn num_asin(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
|||
)
|
||||
}
|
||||
|
||||
/// Num.bitwiseAnd : Int, Int -> Int
|
||||
/// Num.bitwiseAnd : Int a, Int a -> Int a
|
||||
fn num_bitwise_and(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
num_binop(symbol, var_store, LowLevel::NumBitwiseAnd)
|
||||
}
|
||||
|
||||
/// Num.bitwiseXor : Int, Int -> Int
|
||||
/// Num.bitwiseXor : Int a, Int a -> Int a
|
||||
fn num_bitwise_xor(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
num_binop(symbol, var_store, LowLevel::NumBitwiseXor)
|
||||
}
|
||||
|
||||
/// Num.bitwiseOr: Int, Int -> Int
|
||||
/// Num.bitwiseOr: Int a, Int a -> Int a
|
||||
fn num_bitwise_or(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
num_binop(symbol, var_store, LowLevel::NumBitwiseOr)
|
||||
}
|
||||
|
@ -1667,7 +1667,7 @@ fn list_concat(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
|||
)
|
||||
}
|
||||
|
||||
/// List.repeat : elem, Int -> List elem
|
||||
/// List.repeat : elem, Nat -> List elem
|
||||
fn list_repeat(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
let elem_var = var_store.fresh();
|
||||
let len_var = var_store.fresh();
|
||||
|
@ -1809,7 +1809,7 @@ fn list_get(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
|||
)
|
||||
}
|
||||
|
||||
/// List.set : List elem, Int, elem -> List elem
|
||||
/// List.set : List elem, Nat, elem -> List elem
|
||||
///
|
||||
/// List.set :
|
||||
/// Attr (w | u | v) (List (Attr u a)),
|
||||
|
@ -2531,7 +2531,7 @@ fn set_walk(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
|||
)
|
||||
}
|
||||
|
||||
/// Num.rem : Int, Int -> Result Int [ DivByZero ]*
|
||||
/// Num.rem : Int a, Int a -> Result (Int a) [ DivByZero ]*
|
||||
fn num_rem(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
let num_var = var_store.fresh();
|
||||
let unbound_zero_var = var_store.fresh();
|
||||
|
@ -2590,7 +2590,7 @@ fn num_rem(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
|||
)
|
||||
}
|
||||
|
||||
/// Num.isMultipleOf : Int, Int -> Bool
|
||||
/// Num.isMultipleOf : Int a, Int a -> Bool
|
||||
fn num_is_multiple_of(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
lowlevel_2(symbol, LowLevel::NumIsMultipleOf, var_store)
|
||||
}
|
||||
|
@ -2696,7 +2696,7 @@ fn num_div_float(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
|||
)
|
||||
}
|
||||
|
||||
/// Num.div : Int, Int -> Result Int [ DivByZero ]*
|
||||
/// Num.div : Int a , Int a -> Result (Int a) [ DivByZero ]*
|
||||
fn num_div_int(symbol: Symbol, var_store: &mut VarStore) -> Def {
|
||||
let bool_var = var_store.fresh();
|
||||
let num_var = var_store.fresh();
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
[package]
|
||||
name = "roc_gen_dev"
|
||||
description = "The development backend for the Roc compiler"
|
||||
version = "0.1.0"
|
||||
authors = ["The Roc Contributors"]
|
||||
license = "UPL-1.0"
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
[package]
|
||||
name = "roc_gen"
|
||||
name = "roc_gen_llvm"
|
||||
description = "The LLVM backend for the Roc compiler"
|
||||
version = "0.1.0"
|
||||
authors = ["The Roc Contributors"]
|
||||
license = "UPL-1.0"
|
|
@ -49,7 +49,8 @@ use roc_module::ident::TagName;
|
|||
use roc_module::low_level::LowLevel;
|
||||
use roc_module::symbol::{Interns, ModuleId, Symbol};
|
||||
use roc_mono::ir::{
|
||||
BranchInfo, CallType, ExceptionId, JoinPointId, ModifyRc, TopLevelFunctionLayout, Wrapped,
|
||||
BranchInfo, CallType, ExceptionId, JoinPointId, ModifyRc, OptLevel, TopLevelFunctionLayout,
|
||||
Wrapped,
|
||||
};
|
||||
use roc_mono::layout::{Builtin, InPlace, LambdaSet, Layout, LayoutIds, UnionLayout};
|
||||
use target_lexicon::CallingConvention;
|
||||
|
@ -86,21 +87,6 @@ macro_rules! debug_info_init {
|
|||
}};
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum OptLevel {
|
||||
Normal,
|
||||
Optimize,
|
||||
}
|
||||
|
||||
impl From<OptLevel> for OptimizationLevel {
|
||||
fn from(level: OptLevel) -> Self {
|
||||
match level {
|
||||
OptLevel::Normal => OptimizationLevel::None,
|
||||
OptLevel::Optimize => OptimizationLevel::Aggressive,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterate over all functions in an llvm module
|
||||
pub struct FunctionIterator<'ctx> {
|
||||
next: Option<FunctionValue<'ctx>>,
|
||||
|
@ -355,7 +341,9 @@ impl<'a, 'ctx, 'env> Env<'a, 'ctx, 'env> {
|
|||
}
|
||||
|
||||
pub fn module_from_builtins<'ctx>(ctx: &'ctx Context, module_name: &str) -> Module<'ctx> {
|
||||
let bitcode_bytes = bitcode::as_bytes();
|
||||
// In the build script for the builtins module,
|
||||
// we compile the builtins into LLVM bitcode
|
||||
let bitcode_bytes: &[u8] = include_bytes!("../../../builtins/bitcode/builtins.bc");
|
||||
|
||||
let memory_buffer = MemoryBuffer::create_from_memory_range(&bitcode_bytes, module_name);
|
||||
|
||||
|
@ -4558,7 +4546,7 @@ fn run_low_level<'a, 'ctx, 'env>(
|
|||
BasicValueEnum::IntValue(bool_val)
|
||||
}
|
||||
ListGetUnsafe => {
|
||||
// List.get : List elem, Int -> [ Ok elem, OutOfBounds ]*
|
||||
// List.get : List elem, Nat -> [ Ok elem, OutOfBounds ]*
|
||||
debug_assert_eq!(args.len(), 2);
|
||||
|
||||
let (wrapper_struct, list_layout) = load_symbol_and_layout(scope, &args[0]);
|
|
@ -38,7 +38,7 @@ macro_rules! run_jit_function {
|
|||
|
||||
($lib: expr, $main_fn_name: expr, $ty:ty, $transform:expr, $errors:expr) => {{
|
||||
use inkwell::context::Context;
|
||||
use roc_gen::run_roc::RocCallResult;
|
||||
use roc_gen_llvm::run_roc::RocCallResult;
|
||||
use std::mem::MaybeUninit;
|
||||
|
||||
unsafe {
|
||||
|
@ -77,7 +77,7 @@ macro_rules! run_jit_function_dynamic_type {
|
|||
|
||||
($lib: expr, $main_fn_name: expr, $bytes:expr, $transform:expr, $errors:expr) => {{
|
||||
use inkwell::context::Context;
|
||||
use roc_gen::run_roc::RocCallResult;
|
||||
use roc_gen_llvm::run_roc::RocCallResult;
|
||||
|
||||
unsafe {
|
||||
let main: libloading::Symbol<unsafe extern "C" fn(*const u8)> = $lib
|
||||
|
@ -86,7 +86,7 @@ macro_rules! run_jit_function_dynamic_type {
|
|||
.ok_or(format!("Unable to JIT compile `{}`", $main_fn_name))
|
||||
.expect("errored");
|
||||
|
||||
let size = roc_gen::run_roc::ROC_CALL_RESULT_DISCRIMINANT_SIZE + $bytes;
|
||||
let size = roc_gen_llvm::run_roc::ROC_CALL_RESULT_DISCRIMINANT_SIZE + $bytes;
|
||||
let layout = std::alloc::Layout::array::<u8>(size).unwrap();
|
||||
let result = std::alloc::alloc(layout);
|
||||
main(result);
|
|
@ -43,6 +43,12 @@ macro_rules! return_on_layout_error {
|
|||
};
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum OptLevel {
|
||||
Normal,
|
||||
Optimize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum MonoProblem {
|
||||
PatternProblem(crate::exhaustive::Error),
|
||||
|
|
|
@ -6,7 +6,7 @@ license = "UPL-1.0"
|
|||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
roc_gen = { path = "../gen" }
|
||||
roc_gen_llvm = { path = "../gen_llvm" }
|
||||
roc_collections = { path = "../collections" }
|
||||
roc_region = { path = "../region" }
|
||||
roc_module = { path = "../module" }
|
||||
|
|
|
@ -4,8 +4,9 @@ use roc_build::program::FunctionIterator;
|
|||
use roc_can::builtins::builtin_defs_map;
|
||||
use roc_can::def::Def;
|
||||
use roc_collections::all::{MutMap, MutSet};
|
||||
use roc_gen::llvm::externs::add_default_roc_externs;
|
||||
use roc_gen_llvm::llvm::externs::add_default_roc_externs;
|
||||
use roc_module::symbol::Symbol;
|
||||
use roc_mono::ir::OptLevel;
|
||||
use roc_types::subs::VarStore;
|
||||
|
||||
fn promote_expr_to_module(src: &str) -> String {
|
||||
|
@ -180,7 +181,7 @@ pub fn helper<'a>(
|
|||
};
|
||||
|
||||
let builder = context.create_builder();
|
||||
let module = roc_gen::llvm::build::module_from_builtins(context, "app");
|
||||
let module = roc_gen_llvm::llvm::build::module_from_builtins(context, "app");
|
||||
|
||||
// Add roc_alloc, roc_realloc, and roc_dealloc, since the repl has no
|
||||
// platform to provide them.
|
||||
|
@ -190,16 +191,16 @@ pub fn helper<'a>(
|
|||
module.strip_debug_info();
|
||||
|
||||
let opt_level = if cfg!(debug_assertions) {
|
||||
roc_gen::llvm::build::OptLevel::Normal
|
||||
OptLevel::Normal
|
||||
} else {
|
||||
roc_gen::llvm::build::OptLevel::Optimize
|
||||
OptLevel::Optimize
|
||||
};
|
||||
|
||||
let module = arena.alloc(module);
|
||||
let (module_pass, function_pass) =
|
||||
roc_gen::llvm::build::construct_optimization_passes(module, opt_level);
|
||||
roc_gen_llvm::llvm::build::construct_optimization_passes(module, opt_level);
|
||||
|
||||
let (dibuilder, compile_unit) = roc_gen::llvm::build::Env::new_debug_info(module);
|
||||
let (dibuilder, compile_unit) = roc_gen_llvm::llvm::build::Env::new_debug_info(module);
|
||||
|
||||
// mark our zig-defined builtins as internal
|
||||
use inkwell::attributes::{Attribute, AttributeLoc};
|
||||
|
@ -221,7 +222,7 @@ pub fn helper<'a>(
|
|||
}
|
||||
|
||||
// Compile and add all the Procs before adding main
|
||||
let env = roc_gen::llvm::build::Env {
|
||||
let env = roc_gen_llvm::llvm::build::Env {
|
||||
arena: &arena,
|
||||
builder: &builder,
|
||||
dibuilder: &dibuilder,
|
||||
|
@ -235,7 +236,7 @@ pub fn helper<'a>(
|
|||
exposed_to_host: MutSet::default(),
|
||||
};
|
||||
|
||||
let (main_fn_name, main_fn) = roc_gen::llvm::build::build_procedures_return_main(
|
||||
let (main_fn_name, main_fn) = roc_gen_llvm::llvm::build::build_procedures_return_main(
|
||||
&env,
|
||||
opt_level,
|
||||
procedures,
|
||||
|
@ -275,7 +276,7 @@ macro_rules! assert_llvm_evals_to {
|
|||
($src:expr, $expected:expr, $ty:ty, $transform:expr, $leak:expr, $ignore_problems:expr) => {
|
||||
use bumpalo::Bump;
|
||||
use inkwell::context::Context;
|
||||
use roc_gen::run_jit_function;
|
||||
use roc_gen_llvm::run_jit_function;
|
||||
|
||||
let arena = Bump::new();
|
||||
let context = Context::create();
|
||||
|
|
|
@ -63,9 +63,10 @@ pub fn generate(filenames: Vec<PathBuf>, std_lib: StdLib, build_dir: &Path) {
|
|||
// Write each package's module docs html file
|
||||
for (docs_by_id, interns) in package.modules.iter_mut() {
|
||||
for module in docs_by_id.values_mut() {
|
||||
let mut filename = String::new();
|
||||
filename.push_str(module.name.as_str());
|
||||
filename.push_str(".html");
|
||||
let module_dir = build_dir.join(module.name.replace(".", "/").as_str());
|
||||
|
||||
fs::create_dir_all(&module_dir)
|
||||
.expect("TODO gracefully handle not being able to create the module dir");
|
||||
|
||||
let rendered_module = template_html
|
||||
.replace(
|
||||
|
@ -78,7 +79,7 @@ pub fn generate(filenames: Vec<PathBuf>, std_lib: StdLib, build_dir: &Path) {
|
|||
render_main_content(interns, module).as_str(),
|
||||
);
|
||||
|
||||
fs::write(build_dir.join(filename), rendered_module)
|
||||
fs::write(module_dir.join("index.html"), rendered_module)
|
||||
.expect("TODO gracefully handle failing to write html");
|
||||
}
|
||||
}
|
||||
|
@ -228,7 +229,6 @@ fn render_sidebar<'a, I: Iterator<Item = &'a ModuleDocumentation>>(modules: I) -
|
|||
let href = {
|
||||
let mut href_buf = String::new();
|
||||
href_buf.push_str(name);
|
||||
href_buf.push_str(".html");
|
||||
href_buf
|
||||
};
|
||||
|
||||
|
@ -305,7 +305,7 @@ pub fn files_to_documentations(
|
|||
&std_lib,
|
||||
src_dir.as_path(),
|
||||
MutMap::default(),
|
||||
8, // TODO: Is it okay to hardcode ptr_bytes here? I think it should be fine since we'er only type checking (also, 8 => 32bit system)
|
||||
std::mem::size_of::<usize>() as u32, // This is just type-checking for docs, so "target" doesn't matter
|
||||
builtin_defs_map,
|
||||
) {
|
||||
Ok(loaded) => files_docs.push((loaded.documentation, loaded.interns)),
|
||||
|
@ -567,7 +567,7 @@ fn make_doc_link(scope: &mut Scope, interns: &Interns, doc_item: &str) -> String
|
|||
let mut link = String::new();
|
||||
|
||||
link.push_str(module_str);
|
||||
link.push_str(".html#");
|
||||
link.push('#');
|
||||
link.push_str(ident_str);
|
||||
|
||||
let mut buf = String::new();
|
||||
|
@ -583,8 +583,8 @@ fn make_doc_link(scope: &mut Scope, interns: &Interns, doc_item: &str) -> String
|
|||
}
|
||||
Err(_) => {
|
||||
panic!(
|
||||
"Could not find symbol in scope for module link : {}",
|
||||
doc_item
|
||||
"Tried to generate an automatic link in docs for symbol `{}`, but that symbol was not in scope in this module. Scope was: {:?}",
|
||||
doc_item, scope
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,9 +6,9 @@
|
|||
<!-- <title>TODO populate this based on the module's name, e.g. "Parser - roc/parser"</title> -->
|
||||
<!-- <meta name="description" content="TODO populate this based on the module's description"> -->
|
||||
<meta name="viewport" content="width=device-width">
|
||||
<link rel="icon" href="favicon.svg">
|
||||
<script type="text/javascript" src="search.js" defer></script>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<link rel="icon" href="/favicon.svg">
|
||||
<script type="text/javascript" src="/search.js" defer></script>
|
||||
<link rel="stylesheet" href="/styles.css">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
|
|
@ -39,9 +39,11 @@ Nice collection of research on innovative editors, [link](https://futureofcoding
|
|||
* [godbolt.org Compiler Explorer](https://godbolt.org/)
|
||||
* [whitebox debug visualization](https://vimeo.com/483795097)
|
||||
* [Hest](https://ivanish.ca/hest-time-travel/) tool for making highly interactive simulations.
|
||||
* [replit](https://replit.com/) collaborative browser based IDE.
|
||||
* Say you have a failing test that used to work, it would be very valuable to see all code that was changed that was used only by that test.
|
||||
e.g. you have a test `calculate_sum_test` that only uses the function `add`, when the test fails you should be able to see a diff showing only what changed for the function `add`. It would also be great to have a diff of [expression values](https://homepages.cwi.nl/~storm/livelit/images/bret.png) Bret Victor style. An ambitious project would be to suggest or automatically try fixes based on these diffs.
|
||||
* I think it could be possible to create a minimal reproduction of a program / block of code / code used by a single test. So for a failing unit test I would expect it to extract imports, the platform, types and functions that are necessary to run only that unit test and put them in a standalone roc project. This would be useful for sharing bugs with library+application authors and colleagues, for profiling or debugging with all "clutter" removed.
|
||||
* Ability to share program state at a breakpoint with someone else.
|
||||
|
||||
### Cool regular editors
|
||||
|
||||
|
|
|
@ -42,6 +42,23 @@ pub const NODE_BYTES: usize = 32;
|
|||
// usize pointers, which would be too big for us to have 16B nodes.
|
||||
// On the plus side, we could be okay with higher memory usage early on,
|
||||
// and then later use the Mesh strategy to reduce long-running memory usage.
|
||||
//
|
||||
// With this system, we can allocate up to 4B nodes. If we wanted to keep
|
||||
// a generational index in there, like https://crates.io/crates/sharded-slab
|
||||
// does, we could use some of the 32 bits for that. For example, if we wanted
|
||||
// to have a 5-bit generational index (supporting up to 32 generations), then
|
||||
// we would have 27 bits remaining, meaning we could only support at most
|
||||
// 134M nodes. Since the editor has a separate Pool for each module, is that
|
||||
// enough for any single module we'll encounter in practice? Probably, and
|
||||
// especially if we allocate super large collection literals on the heap instead
|
||||
// of in the pool.
|
||||
//
|
||||
// Another possible design is to try to catch reuse bugs using an "ASan" like
|
||||
// approach: in development builds, whenever we "free" a particular slot, we
|
||||
// can add it to a dev-build-only "freed nodes" list and don't hand it back
|
||||
// out (so, we leak the memory.) Then we can (again, in development builds only)
|
||||
// check to see if we're about to store something in zeroed-out memory; if so, check
|
||||
// to see if it was
|
||||
|
||||
#[derive(Debug, Eq)]
|
||||
pub struct NodeId<T> {
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
interface Quicksort exposes [ sortBy, show ] imports []
|
||||
interface Quicksort exposes [ sortBy, sortWith, show ] imports []
|
||||
|
||||
show : List I64 -> Str
|
||||
show = \list ->
|
||||
|
|
23
examples/benchmarks/QuicksortApp.roc
Normal file
23
examples/benchmarks/QuicksortApp.roc
Normal file
File diff suppressed because one or more lines are too long
|
@ -1427,6 +1427,8 @@ Here are various Roc expressions involving operators, and what they desugar to.
|
|||
| `a ^ b` | `Num.pow a b` |
|
||||
| `a % b` | `Num.rem a b` |
|
||||
| `a %% b` | `Num.mod a b` |
|
||||
| `a >> b` | `Num.shr a b` |
|
||||
| `a << b` | `Num.shl a b` |
|
||||
| `-a` | `Num.neg a` |
|
||||
| `-f x y` | `Num.neg (f x y)` |
|
||||
| `a == b` | `Bool.isEq a b` |
|
||||
|
|
1
www/.gitignore
vendored
Normal file
1
www/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
build
|
25
www/build.sh
Executable file
25
www/build.sh
Executable file
|
@ -0,0 +1,25 @@
|
|||
#!/bin/bash
|
||||
|
||||
set -euxo pipefail
|
||||
|
||||
# cd into the directory where this script lives.
|
||||
# This allows us to run this script from the root project directory,
|
||||
# which is what Netlify wants to do.
|
||||
SCRIPT_RELATIVE_DIR=$(dirname "${BASH_SOURCE[0]}")
|
||||
cd $SCRIPT_RELATIVE_DIR
|
||||
|
||||
rm -rf build/
|
||||
cp -r public/ build/
|
||||
|
||||
pushd ..
|
||||
echo 'Generating docs...'
|
||||
# We run the CLI with --no-default-features because that way we don't have the
|
||||
# "llvm" feature and therefore don't depend on LLVM being installed on the
|
||||
# system. (Netlify's build servers have Rust installed, but not LLVM.)
|
||||
#
|
||||
# We set RUSTFLAGS to -Awarnings to ignore warnings during this build,
|
||||
# because when building without "the" llvm feature (which is only ever done
|
||||
# for this exact use case), the result is lots of "unused" warnings!
|
||||
RUSTFLAGS=-Awarnings cargo run -p roc_cli --no-default-features docs compiler/builtins/docs/Bool.roc
|
||||
mv generated-docs/ www/build/builtins
|
||||
popd
|
30
www/netlify.toml
Normal file
30
www/netlify.toml
Normal file
|
@ -0,0 +1,30 @@
|
|||
# This is the file that generates and deploys https://www.roc-lang.org,
|
||||
# which is served on Netlify.
|
||||
#
|
||||
# Netlify's docs for how this configuration file works:
|
||||
# https://docs.netlify.com/routing/headers/#syntax-for-the-netlify-configuration-file
|
||||
[build]
|
||||
publish = "build/"
|
||||
command = "bash build.sh"
|
||||
|
||||
[[headers]]
|
||||
for = "/*"
|
||||
[headers.values]
|
||||
X-Frame-Options = "DENY"
|
||||
X-XSS-Protection = "1; mode=block"
|
||||
Content-Security-Policy = "default-src 'self'; img-src *;"
|
||||
X-Content-Type-Options = "nosniff"
|
||||
|
||||
# Redirect roc-lang.org/authors to the AUTHORS file in this repo
|
||||
#
|
||||
# This is referenced in the LICENSE file, which says to see roc-lang.org/authors
|
||||
# for a list of authors!
|
||||
[[redirects]]
|
||||
from = "/authors"
|
||||
to = "https://github.com/rtfeldman/roc/blob/trunk/AUTHORS"
|
||||
force = true
|
||||
status = 302 # TODO once the repo is public, use status = 200 and this URL:
|
||||
# https://raw.githubusercontent.com/rtfeldman/roc/trunk/AUTHORS
|
||||
#
|
||||
# This way, roc-lang.org/authors will show the authors directly,
|
||||
# proxied from the current AUTHORS file on GitHub, no redirects.
|
4
www/public/favicon.svg
Normal file
4
www/public/favicon.svg
Normal file
|
@ -0,0 +1,4 @@
|
|||
<svg viewBox="0 0 52 53" xmlns="http://www.w3.org/2000/svg">
|
||||
<style>polygon {fill: #5c0bff;}@media (prefers-color-scheme: dark) {polygon {fill: #7733ff;}} </style>
|
||||
<polygon points="0,0 23.8834,3.21052 37.2438,19.0101 45.9665,16.6324 50.5,22 45,22 44.0315,26.3689 26.4673,39.3424 27.4527,45.2132 17.655,53 23.6751,22.7086"/>
|
||||
</svg>
|
After Width: | Height: | Size: 335 B |
23
www/public/index.html
Normal file
23
www/public/index.html
Normal file
|
@ -0,0 +1,23 @@
|
|||
<!doctype html>
|
||||
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
|
||||
<title>The Roc Programming Language</title>
|
||||
<!-- <meta name="description" content="A language for making delightful software."> -->
|
||||
<meta name="viewport" content="width=device-width">
|
||||
|
||||
<!-- <link rel="icon" href="/favicon.svg"> -->
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Work in Progress</h1>
|
||||
<p>Roc's initial release is still under development, and this website is a placeholder until that release is ready.</p>
|
||||
<p>In the meantime, if you'd like to learn more about Roc, here are some videos:</p>
|
||||
<ul>
|
||||
<li><a href="https://youtu.be/FMyyYdFSOHA">Roc on Zig Showtime</a> - April 24, 2021</li>
|
||||
<li><a href="https://youtu.be/ZnYa99QoznE?t=4790">Roc at the Berlin FP Meetup</a> - September 1, 2020 (this one has details on how to try out Roc or get involved)</li>
|
||||
</ul>
|
||||
</body>
|
||||
</html>
|
29
www/public/license/index.html
Normal file
29
www/public/license/index.html
Normal file
|
@ -0,0 +1,29 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
|
||||
<title>Roc's license: The Universal Permissive License (UPL), Version 1.0</title>
|
||||
<meta name="description" content="The software license for the code in the Roc programming language.">
|
||||
<meta name="viewport" content="width=device-width">
|
||||
|
||||
<link rel="icon" href="/favicon.svg">
|
||||
</head>
|
||||
<body><pre><code>Copyright (c) 2019 Richard Feldman and subsequent Roc authors <<a href="https://roc-lang.org/authors">https://roc-lang.org/authors</a>>
|
||||
|
||||
<a href="https://opensource.org/licenses/UPL">The Universal Permissive License (UPL), Version 1.0</a>
|
||||
|
||||
Subject to the condition set forth below, permission is hereby granted to any person obtaining a copy of this software, associated documentation and/or data (collectively the "Software"), free of charge and under any and all copyright rights in the Software, and any and all patent rights owned or freely licensable by each licensor hereunder covering either (i) the unmodified Software as contributed to or provided by such licensor, or (ii) the Larger Works (as defined below), to deal in both
|
||||
|
||||
(a) the Software, and
|
||||
|
||||
(b) any piece of software and/or hardware listed in the lrgrwrks.txt file if one is included with the Software (each a “Larger Work” to which the Software is contributed by such licensors),
|
||||
|
||||
without restriction, including without limitation the rights to copy, create derivative works of, display, perform, and distribute the Software and make, use, sell, offer for sale, import, export, have made, and have sold the Software and the Larger Work(s), and to sublicense the foregoing rights on either these or other terms.
|
||||
|
||||
This license is subject to the following condition:
|
||||
|
||||
The above copyright notice and either this complete permission notice or at a minimum a reference to the UPL must be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</body></code></pre>
|
||||
</html>
|
9
www/public/logo.svg
Normal file
9
www/public/logo.svg
Normal file
|
@ -0,0 +1,9 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="240" height="240" viewBox="0 0 51 53" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M23.6751 22.7086L17.655 53L27.4527 45.2132L26.4673 39.3424L23.6751 22.7086Z" fill="#612BDE"/>
|
||||
<path d="M37.2438 19.0101L44.0315 26.3689L45 22L45.9665 16.6324L37.2438 19.0101Z" fill="#8257E5"/>
|
||||
<path d="M23.8834 3.21052L0 0L23.6751 22.7086L23.8834 3.21052Z" fill="#8257E5"/>
|
||||
<path d="M44.0315 26.3689L23.6751 22.7086L26.4673 39.3424L44.0315 26.3689Z" fill="#8257E5"/>
|
||||
<path d="M50.5 22L45.9665 16.6324L45 22H50.5Z" fill="#612BDE"/>
|
||||
<path d="M23.6751 22.7086L44.0315 26.3689L37.2438 19.0101L23.8834 3.21052L23.6751 22.7086Z" fill="#612BDE"/>
|
||||
</svg>
|
After Width: | Height: | Size: 705 B |
38
www/public/search.js
Normal file
38
www/public/search.js
Normal file
|
@ -0,0 +1,38 @@
|
|||
(function() {
|
||||
let sidebar = document.getElementById("sidebar-nav");
|
||||
let searchBox = document.getElementById("module-search");
|
||||
|
||||
function search() {
|
||||
let text = searchBox.value.toLowerCase(); // Search is case-insensitive.
|
||||
|
||||
if (text === "") {
|
||||
// Un-hide everything
|
||||
sidebar.querySelectorAll(".sidebar-entry a").forEach((entry) => entry.classList.remove("hidden"));
|
||||
|
||||
// Re-hide all the sub-entries except for those of the first module
|
||||
sidebar.querySelectorAll(".sidebar-entry:not(:first-of-type) .sidebar-sub-entries a").forEach((entry) => entry.classList.add("hidden"));
|
||||
} else {
|
||||
// First, show/hide all the sub-entries within each module (top-level functions etc.)
|
||||
sidebar.querySelectorAll(".sidebar-sub-entries a").forEach((entry) => {
|
||||
if (entry.textContent.toLowerCase().includes(text)) {
|
||||
entry.classList.remove("hidden");
|
||||
} else {
|
||||
entry.classList.add("hidden");
|
||||
}
|
||||
});
|
||||
|
||||
// Then, show/hide modules based on whether they match, or any of their sub-entries matched
|
||||
sidebar.querySelectorAll(".sidebar-module-link").forEach((entry) => {
|
||||
if (entry.textContent.toLowerCase().includes(text) || entry.parentNode.querySelectorAll(".sidebar-sub-entries a:not(.hidden)").length > 0) {
|
||||
entry.classList.remove("hidden");
|
||||
} else {
|
||||
entry.classList.add("hidden");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
searchBox.addEventListener("input", search);
|
||||
|
||||
search();
|
||||
})();
|
479
www/public/styles.css
Normal file
479
www/public/styles.css
Normal file
|
@ -0,0 +1,479 @@
|
|||
:root {
|
||||
--link-color: #612bde;
|
||||
--code-link-color: #5721d4;
|
||||
--text-color: #333333;
|
||||
--code-color: #222222;
|
||||
--code-bg-color: #eeeeee;
|
||||
--body-bg-color: #fdfdfd;
|
||||
--border-color: #e9e9e9;
|
||||
--faded-color: #4c4c4c;
|
||||
--monospace-font;
|
||||
--font-sans: -apple-system, BlinkMacSystemFont, Roboto, Helvetica, Arial, sans-serif;
|
||||
--font-mono: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace;
|
||||
--top-header-height: 67px;
|
||||
--sidebar-width: 280px;
|
||||
--top-bar-bg: #8257e5;
|
||||
--top-bar-fg: #ffffff;
|
||||
--nav-link-hover-color: #000000;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #972395;
|
||||
}
|
||||
|
||||
.logo {
|
||||
padding: 2px 8px;
|
||||
}
|
||||
|
||||
.logo svg {
|
||||
height: 48px;
|
||||
width: 48px;
|
||||
fill: var(--top-bar-fg);
|
||||
}
|
||||
|
||||
.logo:hover {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.logo svg:hover {
|
||||
fill: var(--nav-link-hover-color);
|
||||
}
|
||||
|
||||
.pkg-full-name {
|
||||
color: var(--text-color);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-size: 32px;
|
||||
margin: 0 8px;
|
||||
font-weight: normal;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.pkg-full-name a {
|
||||
padding-top: 12px;
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.pkg-and-logo {
|
||||
min-width: 0; /* necessary for text-overflow: ellipsis to work in descendants */
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
background-color: var(--top-bar-bg);
|
||||
}
|
||||
|
||||
.pkg-and-logo a, .pkg-and-logo a:visited {
|
||||
color: var(--top-bar-fg);
|
||||
}
|
||||
|
||||
.pkg-and-logo a:hover {
|
||||
color: var(--nav-link-hover-color);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.main-container {
|
||||
min-width: 0; /* necessary for text-overflow: ellipsis to work in descendants */
|
||||
}
|
||||
|
||||
.search-button {
|
||||
flex-shrink: 0; /* always shrink the package name before these; they have a relatively constrained length */
|
||||
padding: 12px 18px;
|
||||
margin-right: 42px;
|
||||
display: none; /* only show this in the mobile view */
|
||||
}
|
||||
|
||||
.version {
|
||||
padding: 18px 10px;
|
||||
min-width: 48px;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
body {
|
||||
display: grid;
|
||||
grid-template-columns: [before-sidebar] 1fr [sidebar] var(--sidebar-width) [main-content] fit-content(calc(1280px - var(--sidebar-width))) [end] 1fr;
|
||||
grid-template-rows: [top-header] var(--top-header-height) [above-footer] auto [footer] auto;
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-family: var(--font-sans);
|
||||
color: var(--text-color);
|
||||
background-color: var(--body-bg-color);
|
||||
}
|
||||
|
||||
main {
|
||||
grid-column-start: main-content;
|
||||
grid-column-end: main-content;
|
||||
grid-row-start: above-footer;
|
||||
grid-row-end: above-footer;
|
||||
box-sizing: border-box;
|
||||
position: relative;
|
||||
font-size: 18px;
|
||||
line-height: 1.85em;
|
||||
margin-top: 2px;
|
||||
padding: 48px;
|
||||
}
|
||||
|
||||
#sidebar-nav {
|
||||
grid-column-start: sidebar;
|
||||
grid-column-end: sidebar;
|
||||
grid-row-start: above-footer;
|
||||
grid-row-end: above-footer;
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-sizing: border-box;
|
||||
padding-left: 56px;
|
||||
padding-top: 6px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.top-header-extension {
|
||||
grid-column-start: before-sidebar;
|
||||
grid-column-end: sidebar;
|
||||
grid-row-start: top-header;
|
||||
grid-row-end: top-header;
|
||||
background-color: var(--top-bar-bg);
|
||||
}
|
||||
|
||||
.top-header {
|
||||
grid-column-start: sidebar;
|
||||
grid-column-end: end;
|
||||
grid-row-start: top-header;
|
||||
grid-row-end: top-header;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
flex-wrap: nowrap;
|
||||
flex-grow: 1;
|
||||
box-sizing: border-box;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 24px;
|
||||
height: 100%;
|
||||
min-width: 0; /* necessary for text-overflow: ellipsis to work in descendants */
|
||||
}
|
||||
|
||||
.top-header-triangle {
|
||||
/* This used to be a clip-path, but Firefox on Android (at least as of early 2020)
|
||||
* rendered the page extremely slowly in that version. With this approach it's super fast.
|
||||
*/
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-style: solid;
|
||||
border-width: var(--top-header-height) 0 0 48px;
|
||||
border-color: transparent transparent transparent var(--top-bar-bg);
|
||||
}
|
||||
|
||||
p {
|
||||
overflow-wrap: break-word;
|
||||
margin: 24px 0;
|
||||
}
|
||||
|
||||
footer {
|
||||
grid-column-start: main-content;
|
||||
grid-column-end: main-content;
|
||||
grid-row-start: footer;
|
||||
grid-row-end: footer;
|
||||
max-width: var(--main-content-max-width);
|
||||
font-size: 14px;
|
||||
box-sizing: border-box;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
footer p {
|
||||
display: inline-block;
|
||||
margin-top: 0;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.content {
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.sidebar-entry ul {
|
||||
list-style-type: none;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.sidebar-entry a {
|
||||
box-sizing: border-box;
|
||||
min-height: 48px;
|
||||
min-width: 48px;
|
||||
padding: 12px 16px;
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.sidebar-sub-entries a {
|
||||
display: block;
|
||||
line-height: 24px;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
padding-left: 36px;
|
||||
}
|
||||
|
||||
.module-name {
|
||||
font-size: 56px;
|
||||
line-height: 1em;
|
||||
font-family: var(--font-mono);
|
||||
font-weight: bold;
|
||||
margin-top: 18px;
|
||||
margin-bottom: 48px;
|
||||
}
|
||||
|
||||
.module-name a, .module-name a:visited {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.sidebar-module-link {
|
||||
box-sizing: border-box;
|
||||
font-size: 18px;
|
||||
line-height: 24px;
|
||||
font-family: var(--font-mono);
|
||||
font-weight: bold;
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 8px 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
a, a:visited {
|
||||
color: var(--link-color);
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 32px;
|
||||
margin: 48px 0 24px 0;
|
||||
}
|
||||
|
||||
h4 {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.type-def {
|
||||
font-size: 24px;
|
||||
color: var(--link-color);
|
||||
}
|
||||
|
||||
.code-snippet {
|
||||
padding: 12px 16px;
|
||||
display: block;
|
||||
box-sizing: border-box;
|
||||
font-family: var(--font-mono);
|
||||
background-color: var(--code-bg-color);
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: var(--font-mono);
|
||||
color: var(--code-color);
|
||||
background-color: var(--code-bg-color);
|
||||
padding: 2px 8px;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
code a {
|
||||
color: var(--code-link-color);
|
||||
}
|
||||
|
||||
code a:visited {
|
||||
color: var(--code-link-color);
|
||||
}
|
||||
|
||||
pre {
|
||||
margin: 36px 0;
|
||||
padding: 8px;
|
||||
box-sizing: border-box;
|
||||
background-color: var(--code-bg-color);
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
pre code {
|
||||
padding: 6px 8px;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
/* Use !important to win all specificity fights. */
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
#module-search:placeholder-shown {
|
||||
padding: 0;
|
||||
opacity: 0;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
#module-search, #module-search:focus {
|
||||
opacity: 1;
|
||||
padding: 12px 16px;
|
||||
height: 48px;
|
||||
}
|
||||
|
||||
/* Show the "Search" label link when the text input has a placeholder */
|
||||
#module-search:placeholder-shown + #search-link {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
/* Hide the "Search" label link when the text input has focus */
|
||||
#module-search:focus + #search-link {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#module-search {
|
||||
display: block;
|
||||
box-sizing: border-box;
|
||||
background-color: var(--code-bg-color);
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
font-size: 18px;
|
||||
line-height: 18px;
|
||||
margin-top: 6px;
|
||||
border: none;
|
||||
color: var(--faded-color);
|
||||
background-color: var(--code-bg-color);
|
||||
font-family: var(--font-serif);
|
||||
}
|
||||
|
||||
#module-search::placeholder {
|
||||
color: var(--faded-color);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
#search-link {
|
||||
box-sizing: border-box;
|
||||
display: none;
|
||||
align-items: center;
|
||||
font-size: 18px;
|
||||
line-height: 18px;
|
||||
padding: 12px 16px;
|
||||
height: 48px;
|
||||
cursor: pointer;
|
||||
color: var(--link-color);
|
||||
}
|
||||
|
||||
#search-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--body-bg-color: #303030;
|
||||
--code-bg-color: #393939;
|
||||
--border-color: #555555;
|
||||
--code-color: #eeeeee;
|
||||
--text-color: #cccccc;
|
||||
--logo-solid: #777777;
|
||||
--faded-color: #bbbbbb;
|
||||
--link-color: #c5a8ff;
|
||||
--code-link-color: #b894ff;
|
||||
--top-bar-bg: #6845b9;
|
||||
--top-bar-fg: #eeeeee;
|
||||
}
|
||||
|
||||
html {
|
||||
scrollbar-color: #444444 #2f2f2f;
|
||||
}
|
||||
}
|
||||
|
||||
@media only screen and (max-device-width: 480px) {
|
||||
.search-button {
|
||||
display: block; /* This is only visible in mobile. */
|
||||
}
|
||||
|
||||
.top-header {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.pkg-full-name {
|
||||
margin-left: 8px;
|
||||
margin-right: 12px;
|
||||
font-size: 24px;
|
||||
padding-bottom: 14px;
|
||||
}
|
||||
|
||||
.pkg-full-name a {
|
||||
vertical-align: middle;
|
||||
padding: 18px 0;
|
||||
}
|
||||
|
||||
.logo {
|
||||
padding-left: 2px;
|
||||
width: 50px;
|
||||
height: 54px;
|
||||
}
|
||||
|
||||
.version {
|
||||
margin: 0;
|
||||
font-weight: normal;
|
||||
font-size: 18px;
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
|
||||
.module-name {
|
||||
font-size: 36px;
|
||||
margin-top: 8px;
|
||||
margin-bottom: 8px;
|
||||
max-width: calc(100% - 18px);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
main {
|
||||
padding: 18px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.container {
|
||||
margin: 0;
|
||||
min-width: 320px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.content {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
margin-top: 0;
|
||||
padding-left: 0;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
#sidebar-heading {
|
||||
font-size: 24px;
|
||||
margin: 16px;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 18px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
h4 {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.top-header {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.content {
|
||||
/* Display the sidebar below <main> without affecting tab index */
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue