* parser now parses expression like the C++ compiler does
* This makes initializers work
* Added control flow expression (only return is parsed)
* Added catch parsing (It doesn't quite work)
* The parse can now specify states as optional.
* The parse will roll back on error if states are optional
* This can be overriden by State.Required
We now use a generic Rand structure which abstracts the core functions
from the backing engine.
The old Mersenne Twister engine is removed and replaced instead with
three alternatives:
- Pcg32
- Xoroshiro128+
- Isaac64
These should provide sufficient coverage for most purposes, including a
CSPRNG using Isaac64. Consumers of the library that do not care about
the actual engine implementation should use DefaultPrng and DefaultCsprng.
* @panic generates an error return trace
* printing an error return trace no longer interferes with
normal stack traces.
* instead of ignore_frame_count, we look at the return address
when you call panic, and that's the first stack trace function
makes stack traces much cleaner - the error return trace
flows gracefully into the stack trace
Issue #699 since fixed. Nearly a x3 perf improvement.
Using --release-fast.
Sha3_256 (before): 96 Mb/s
Sha3_256 (after): 267 Mb/s
Sha3_512 (before): 53 Mb/s
Sha3_512 (after): 142 Mb/s
No real gains from unrolling other initialization loops in crypto
functions so have been left as is.
The names of these functions should probably change, but at least
the semantics are correct now:
* type_is_codegen_pointer - the type is either a fn, ptr, or promise
* get_codegen_ptr_type -
- ?&T and &T returns &T
- ?promise and promise returns promise
- ?fn()void and fn()void returns fn()void
- otherwise returns nullptr
Add basic address->symbol resolution support. Uses symtab data from the
MachO image, not external dSYM data; that's left as a future exercise.
The net effect is that we can now map addresses to function names but
not much more. File names and line number data will have to wait until
a future pull request.
Partially fixes#434.
Use std.heap.FixedBufferAllocator combined with
std.heap.DirectAllocator instead.
std.mem.FixedBufferAllocator is moved to std.heap.FixedBufferAllocator
* DirectAllocator does the underlying syscall for every allocation.
* ArenaAllocator takes another allocator as an argument and
allocates bytes up front, falling back to DirectAllocator with
increasingly large allocation sizes, to avoid calling it too often.
Then the entire arena can be freed at once.
The self hosted parser is updated to take advantage of ArenaAllocator
for the AST that it returns. This significantly reduces the complexity
of cleanup code.
docgen and build runner are updated to use the combination of
ArenaAllocator and DirectAllocator instead of IncrementingAllocator,
which is now deprecated in favor of FixedBufferAllocator combined
with DirectAllocator.
The C allocator calls aligned_alloc instead of malloc, in order to
respect the alignment parameter.
Added asserts in Allocator to ensure that implementors of the
interface return slices of the correct size.
Fixed a bug in Allocator when you call realloc to grow the allocation.
* move std.io.File to std.os.File
* add `zig fmt` to self hosted compiler
* introduce std.io.BufferedAtomicFile API
* introduce std.os.AtomicFile API
* add `std.os.default_file_mode`
* change FileMode on posix from being a usize to a u32
* add std.os.File.mode to return mode of an open file
* std.os.copyFile copies the mode from the source file instead of
using the default file mode for the dest file
* move `std.os.line_sep` to `std.cstr.line_sep`
Before we accepted a nullable allocator for some stuff like
opening files. Now we require an allocator.
Use the mem.FixedBufferAllocator pattern if a bound on the amount
to allocate is known.
This also establishes the pattern that usually an allocator is the
first argument to a function (possibly after "self").
fix docs for std.cstr.addNullByte
self hosted compiler:
* only build docs when explicitly asked to
* clean up main
* stub out zig fmt
at - Get the item at the n-th index.
insert - Insert and item into the middle of the list, resizing and copying
existing elements if needed.
insertSlice - Insert a slice into the middle of the list, resizing and
copying existing elements if needed.
Add fallback paths for when the getrandom(2) system call is not
available. Try /dev/urandom first and sysctl(RANDOM_UUID) second.
The sysctl issues a warning in the system logs with some kernels but
that seems like an acceptable tradeoff for the fallback of a fallback.
The purpose of this is:
* Only one way to do things
* Changing a function with void return type to return a possible
error becomes a 1 character change, subtly encouraging
people to use errors.
See #632
Here are some imperfect sed commands for performing this update:
remove arrow:
```
sed -i 's/\(\bfn\b.*\)-> /\1/g' $(find . -name "*.zig")
```
add void:
```
sed -i 's/\(\bfn\b.*\))\s*{/\1) void {/g' $(find ../ -name "*.zig")
```
Some cleanup may be necessary, but this should do the bulk of the work.
* docgen supports obj_err code kind for demonstrating
errors without explicit test cases
* add documentation for `extern enum`. See #367
* remove coldcc keyword and add @setIsCold. See #661
* add compile errors for non-extern struct, enum, unions
in function signatures
* add .h file generation for extern struct, enum, unions
These are on the slower side and could be improved. No performance optimizations
yet have been done.
```
Cpu: Intel(R) Core(TM) i5-6500 CPU @ 3.20GHz
```
-- Sha3-256
```
Zig --release-fast
93 Mb/s
Zig --release-safe
99 Mb/s
Zig
4 Mb/s
```
-- Sha3-512
```
Zig --release-fast
49 Mb/s
Zig --release-safe
54 Mb/s
Zig
2 Mb/s
```
Interestingly, release-safe is producing slightly better code than
release-fast.
* error return tracing is disabled in release-fast mode
* add @errorReturnTrace
* zig build API changes build return type from `void` to `%void`
* allow `void`, `noreturn`, and `u8` from main. closes#535
Some performance comparisons to C.
We take the fastest time measurement taken across multiple runs.
The block hashing functions use the same md5/sha1 methods.
```
Cpu: Intel(R) Core(TM) i5-6500 CPU @ 3.20GHz
Gcc: 7.2.1 20171224
Clang: 5.0.1
Zig: 0.1.1.304f6f1d
```
See https://www.nayuki.io/page/fast-md5-hash-implementation-in-x86-assembly:
```
gcc -O2
661 Mb/s
clang -O2
490 Mb/s
zig --release-fast and zig --release-safe
570 Mb/s
zig
50 Mb/s
```
See https://www.nayuki.io/page/fast-sha1-hash-implementation-in-x86-assembly:
```
gcc -O2
588 Mb/s
clang -O2
563 Mb/s
zig --release-fast and zig --release-safe
610 Mb/s
zig
21 Mb/s
```
In short, zig provides pretty useful tools for writing this sort of
code. We are in the lead against clang (which uses the same LLVM
backend) with us being slower only against md5 with GCC.
* better error message for realpath failing
* fix bug in std.io.readFileAllocExtra incorrectly returning
error.EndOfStream
* implement std.os.selfExePath and std.os.selfExeDirPath for windows
Before:
* IR basic blocks are in arbitrary order
* when doing an IR pass, when a block is encountered, code
must look at all the instructions in the old basic block,
determine what blocks are referenced, and queue up those
old basic blocks first.
* This had a bug (See #667)
Now:
* IR basic blocks are required to be in an order that guarantees
they will be referenced by a branch, before any instructions
within are referenced.
ir pass1 is updated to meet this constraint.
* When doing an IR pass, we iterate over old basic blocks
in the order they appear. Blocks which have not been
referenced are discarded.
* After the pass is complete, we must iterate again to look
for old basic blocks which now point to incomplete new
basic blocks, due to comptime code generation.
* This last part can probably be optimized - most of the time
we don't need to iterate over the basic block again.
closes#667
...field to const slice parameter
we use a packed struct internally to represent a const array
of disparate union values, and needed to update the internal
getelementptr instruction to recognize that.
closes#664
closes#346closes#630
regression: translate-c can no longer translate switch statements.
after #629 we can ressurect and modify the code to utilize arbitrarily
returning from blocks.
introduces the `@export` builtin function which can be used
in a comptime block to conditionally export a function.
it also allows creation of aliases.
previous export syntax is still allowed.
closes#462closes#420
* add @noInlineCall - see #640
This fixes a crash in --release-safe and --release-fast modes
where the optimizer inlines everything into _start and
clobbers the command line argument data.
If we were able to verify that the user's code never reads
command line args, we could leave off this "no inline"
attribute.
* add i29 and u29 primitive types. u29 is the type of alignment,
so it makes sense to be a primitive.
probably in the future we'll make any `i` or `u` followed by
digits into a primitive.
* add `aligned` functions to Allocator interface
* add `os.argsAlloc` and `os.argsFree` so that you can get
a `[]const []u8`, do whatever arg parsing you want, and then free
it. For now this uses the other API under the hood, but it could
be reimplemented to do a single allocation.
* add tests to make sure command line argument parsing works.
* @enumTagName renamed to @tagName and it works on enums and
union-enums
* Remove the EnumTag type. Now there is only enum and union,
and the tag type of a union is always an enum.
* unions support specifying the tag enum type, and they support
inferring an enum tag type.
* Enums no longer support field types but they do support
setting the tag values. Likewise union-enums when inferring
an enum tag type support setting the tag values.
* It is now an error for enums and unions to have 0 fields.
* switch statements support union-enums
closes#618
* rename decode to decodeExactUnsafe.
* add decodeExact, which checks for invalid chars and padding.
* add decodeWithIgnore, which also allows ignoring chars.
* alphabets are supplied to the decoders with their
char-to-index mapping already built, which enables it to be
done at comptime.
* all decode/encode apis except decodeWithIgnore require dest
to be the exactly correct length. This is calculated by a
calc function corresponding to each api. These apis no longer
return the dest parameter.
* for decodeWithIgnore, an exact size cannot be known a priori.
Instead, a calc function gives an upperbound, and a runtime
error is returned in case of overflow. decodeWithIgnore
returns the number of bytes written to dest.
closes#611
* fix fstat wrong on darwin
* move std.debug.global_allocator to std.debug.global_allocator_state and make it private
* add std.debug.global_allocator as a pointer (to upgrade your zig code remove
the '&')
I started working on #465 and made some corresponding std.io
API changes.
New structs:
* std.io.FileInStream
* std.io.FileOutStream
* std.io.BufferedOutStream
* std.io.BufferedInStream
Removed:
* std.io.File.in_stream
* std.io.File.out_stream
Now instead of &file.out_stream or &file.in_stream to get access to
the stream API for a file, you get it like this:
var file_in_stream = io.FileInStream.init(&file);
const in_stream = &file_in_stream.stream;
var file_out_stream = io.FileOutStream.init(&file);
const out_stream = &file_out_stream.stream;
This is evidence that we might not need any OOP features -
See #130.
* Merge io.InStream and io.OutStream into io.File
* Introduce io.OutStream and io.InStream interfaces
- io.File implements both of these
* Move mem.IncrementingAllocator to heap.IncrementingAllocator
Instead of:
```
%return std.io.stderr.printf("hello\n");
```
now do:
```
std.debug.warn("hello\n");
```
To print to stdout, see `io.getStdOut()`.
* Rename std.ArrayList.resizeDown to std.ArrayList.shrink.
the optimizer was deleting compiler_rt symbols, so I changed
the linkage type from LinkOnce to Weak
also changed LinkOnce to mean linkonce_odr in llvm and
Weak to mean weak_odr in llvm.
See #563
I had to revert the target native features thing because there
is still some incorrect behavior with f128.
Reopens#508
partially reverts b505462509
See #302
* add alignment capability for fn protos
* add @alignCast
* fix some ast rendering code
* fix some ir rendering code
* add error for pointer cast increasing alignment
* update allocators in std to correctly align
See #37
* remove `@setGlobalAlign`
* add align keyword for setting alignment on functions and
variables.
* loads and stores use alignment from pointer
* memcpy, memset use alignment from pointer
* add syntax for pointer alignment
* slices can have volatile
* add u2, i2 primitives
* ignore preferred align and use abi align everywhere
* back to only having alignOf builtin.
preferredAlignOf is too tricky to be useful.
See #432. Partial revert of
e726925e80.
See #37
* try some macos travis stuff
* put c in the link libs for macos since we always link with libSystem
* for non-native targets on macos, allow runtime symbol resolution
- it's causing an infinite loop in LLD.
* for macos, always build compiler_rt and turn on LinkOnce because
compiler_rt on darwin is missing some stuff.
previously we used the bigfloat abstraction to do all
compile-time float math. but runtime code and comptime code
are supposed to get the same result. so now if you add a
f32 to a f32 at compile time it does it with f32 math
instead of the bigfloat. float literals still get the
bigfloat math.
closes#424
* add u3, u4, u5, u6, u7 and i3, i4, i5, i6, i7
* shift operations shift amount parameter type is
integer with log2 bit width of other param
- This enforces not violating undefined behavior on
shift amount >= bit width with the type system
* clean up math.log, math.ln, math.log2, math.log10
closes#403
Before:
* << is left shift, not allowed to shift 1 bits out
* <<% is left shift, allowed to shift 1 bits out
* >> is right shift, allowed to shift 1 bits out
After:
* << is left shift, allowed to shift 1 bits out
* >> is right shift, allowed to shift 1 bits out
* @shlExact is left shift, not allowed to shift 1 bits out
* @shrExact is right shift, not allowed to shift 1 bits out
Closes#413
This merges the standard library math functions that
Marc Tiehuis (@tiehuis) has been working on. Marc has
joined the Zig organization and now has commit access.
Thank you for this huge contribution to Zig.
Closes#374.
This does not fix the underlying issue in pow at this stage, but we may
be able to narrow down the cause after adding tests for specific edge
cases in functions.
This covers the majority of the functions as covered by the C99
specification for a math library.
Code is adapted primarily from musl libc, with the pow and standard
trigonometric functions adapted from the Go stdlib.
Changes:
- Remove assert expose in index and import as needed.
- Add float log function and merge with existing base 2 integer
implementation.
See https://github.com/tiehuis/zig-fmath.
See #374.
* skip installing std/rand_test.zig as it's not needed beyond running
the std lib tests
* add std.math.floor function
* add setFloatMode builtin function to choose between
builtin.FloatMode.Optimized (default) and builtin.FloatMode.Strict
(Optimized is equivalent to -ffast-math in gcc)
* add `@divTrunc` and `@divFloor` functions
* add `@rem` and `@mod` functions
* add compile error for `/` and `%` with signed integers
* add `.bit_count` for float primitive types
closes#217
Old:
```
while (condition; expression) {}
```
New:
```
while (condition) : (expression) {}
```
This is in preparation to allow nullable and
error union types as the condition. See #357
this reverts 5c04730534.
sadly the quality of the intel dialect in llvm's assembly
parser has many frustrating bugs, and generally has unfortunate
syntax.
the plan is to use AT&T for now since it at least works,
and eventually zig will have its own assembly parser for
x86 and it will be as close to NASM as possible.
* add ability to add assembly files when building an exe, obj, or lib
* add implicit cast from `[N]T` to `?[]const T` (closes#343)
* remove link_exe and link_lib in favor of allowing build_exe and
build_lib support no root zig source file
closes#291
This changes the error message "return value ignored" to "expression value is ignored".
This is because this error also applies to {1;}, which has no function calls.
Also fix ignored expression values in std and test.
This caught a bug in debug.readAllocBytes where an early Eof error would have been missed.
See #219.
See #329
Supporting work:
* move std.cstr.Buffer0 to std.buffer.Buffer
* add build.zig to example/shared_library/ and add an automated test
for it
* add std.list.List.resizeDown
* improve std.os.makePath
- no longer recursive
- takes into account . and ..
* add std.os.path.isAbsolute
* add std.os.path.resolve
* reimplement std.os.path.dirname
- no longer requires an allocator
- handles edge cases correctly
* add std.os.deleteTree
* add std.os.deleteDir
* add std.os.page_size
* add std.os API for iterating over directories
* refactor duplication in build.zig
* update documentation on how to run tests
* zig build system: create standard dynamic library sym links
* unwrapping an error results in a panic message that contains
the error name
* rename error.SysResources to error.SystemResources
* add std.os.symLink
* add std.os.deleteFile
where Int is an integer type
also introduce `@intToPtr` builtin for converting a usize
to a pointer. users now have to use this instead of `(&T)(int)`.
closes#311
* Fix assertion failure when switching on type.
Closes#310
* Update zig build system to support user defined options.
See #204
* fmt.format supports {sNNN} to set padding for a buffer arg.
* add std.fmt.bufPrint and std.fmt.allocPrint
* std.hash_map.HashMap.put returns the previous value
* add std.mem.startsWith
* See #204 - zig build system
* allow builtin types Os, Environ, Arch to be used at runtime.
they have zero_bits=false and debug info now.
* Eradicate use of `@alloca` in std for syscalls. See #225
* add `std.io.writeFile`
* `std.debug.panic` adds a newline to format
* In-progress os.ChildProcess.spawn implementation. See #204
* Add explicit cast from integer to error. Closes#294
* fix casting from error to integer
* fix compiler crash when initializing variable to undefined
with no type
* `zig build --export [obj|lib|exe]` changed to `zig build_obj`,
`zig build_lib` and `zig build_exe` respectively.
* `--name` parameter is optional when it can be inferred from the
root source filename. closes#207
* `zig build` now looks for `build.zig` which interacts with
`std.build.Builder` to describe the targets, and then the zig
build system prints TODO: build these targets. See #204
* add `@bitcast` which is mainly used for pointer reinterpret
casting and make explicit casting not do pointer reinterpretation.
Closes#290
* fix debug info for byval parameters
* sort command line help options
* `std.debug.panic` supports format string printing
* add `std.mem.IncrementingAllocator`
* fix const ptr to a variable with data changing at runtime.
closes#289
* introduce zigrt file. it contains only weak symbols so that
multiple instances can be merged. it contains __zig_panic
so that multiple .o files can call the same panic function.
* remove `@setFnVisible` builtin and add @setGlobalLinkage builtin
which is more powerful
* add `@panic` builtin function.
* fix collision of symbols with extern prototypes and internal
function names
* add stack protector safety when linking against libc. To add
the safety mechanism without libc requires implementing
Thread Local Storage. See #276
* standard library knows if it is linking against libc and will
sometimes call libc functions in that case instead of providing
redundant definitions
* fix infinite loop bug when resolving use declarations
* allow calling the same C function from different C imports.
closes#277
* push more logic from compiler to std/bootstrap.zig
* standard library provides way to access errno
closes#274
* fix compile error in standard library for windows
* add implementation of getRandomBytes for windows
* `@truncate` builtin allows casting to the same size integer.
It also performs two's complement casting between signed and
unsigned integers.
* The idiomatic way to convert between bytes and numbers is now
`mem.readInt` and `mem.writeInt` instead of an unsafe cast.
It works at compile time, is safer, and looks cleaner.
* Implicitly casting an array to a slice is allowed only if the
slice is const.
* Constant pointer values know if their memory is from a compile-
time constant value or a compile-time variable.
* Cast from [N]u8 to []T no longer allowed, but [N]u8 to []const T
still allowed.
* Fix inability to pass a mutable pointer to comptime variable at
compile-time to a function and have the function modify the
memory pointed to by the pointer.
* Add the `comptime T: type` parameter back to mem.eql. Prevents
accidentally creating instantiations for arrays.
* add `@compileLog(...)` builtin function
- Helps debug code running at compile time
- See #240
* fix crash when there is an error on the start value of a slice
* add implicit cast from int and float types to int and float
literals if the value is known at compile time
* make array concatenation work with slices in addition to
arrays and c string literals
* fix compile error message for something not having field access
* fix crash when `@setDebugSafety()` was called from a
function being evaluated at compile-time
* fix compile-time evaluation of overflow math builtins.
* avoid debug safety panic handler in builtin.o and compiler_rt.o
since we use no debug safety in these modules anyway
* add compiler_rt functions for division on ARM
- Closes#254
* move default panic handler to std.debug so users can
call it manually
* std.io.printf supports a width in the format specifier
remove "unnecessary if statement" error
this "depends on compile variable" code is too hard to validate,
and has false negatives. not worth it right now.
std.str removed, instead use std.mem.
std.mem.eql and std.mem.sliceEql merged and do not require explicit
type argument.
* instead of emitting a breakpoint for a debug safety crash,
zig calls a panic function which prints an error message
and a stack trace and then calls abort.
* on freestanding OS, this panic function has a default
implementation of a simple infinite loop.
* users can override the panic implementation by providing
`pub fn panic(message: []const u8) -> unreachable { }`
* workaround for LLVM segfaulting when you try to use cold
calling convention on ARM.
closes#245
if and switch are implicitly inline if the condition/target
expression is known at compile time.
instead of:
```
inline if (condition) ...
inline switch (target) ...
```
one can use:
```
if (comptime condition) ...
switch (comptime target) ...
```
See #167
Need to troubleshoot when we send 2 slices to printf. It goes
into an infinite loop.
This commit introduces 4 builtin functions:
* `@isInteger`
* `@isFloat`
* `@canImplictCast`
* `@typeName`