Initial commit
[yaffs-website] / node_modules / node-sass / src / libsass / docs / api-function-example.md
1 ## Example main.c
2
3 ```C
4 #include <stdio.h>
5 #include <stdint.h>
6 #include "sass/context.h"
7
8 union Sass_Value* call_fn_foo(const union Sass_Value* s_args, Sass_Function_Entry cb, struct Sass_Compiler* comp)
9 {
10   // get context/option struct associated with this compiler
11   struct Sass_Context* ctx = sass_compiler_get_context(comp);
12   struct Sass_Options* opts = sass_compiler_get_options(comp);
13   // get information about previous importer entry from the stack
14   Sass_Import_Entry import = sass_compiler_get_last_import(comp);
15   const char* prev_abs_path = sass_import_get_abs_path(import);
16   const char* prev_imp_path = sass_import_get_imp_path(import);
17   // get the cookie from function descriptor
18   void* cookie = sass_function_get_cookie(cb);
19   // we actually abuse the void* to store an "int"
20   return sass_make_number((intptr_t)cookie, "px");
21 }
22
23 int main( int argc, const char* argv[] )
24 {
25
26   // get the input file from first argument or use default
27   const char* input = argc > 1 ? argv[1] : "styles.scss";
28
29   // create the file context and get all related structs
30   struct Sass_File_Context* file_ctx = sass_make_file_context(input);
31   struct Sass_Context* ctx = sass_file_context_get_context(file_ctx);
32   struct Sass_Options* ctx_opt = sass_context_get_options(ctx);
33
34   // allocate a custom function caller
35   Sass_Function_Entry fn_foo =
36     sass_make_function("foo()", call_fn_foo, (void*)42);
37
38   // create list of all custom functions
39   Sass_Function_List fn_list = sass_make_function_list(1);
40   sass_function_set_list_entry(fn_list, 0, fn_foo);
41   sass_option_set_c_functions(ctx_opt, fn_list);
42
43   // context is set up, call the compile step now
44   int status = sass_compile_file_context(file_ctx);
45
46   // print the result or the error to the stdout
47   if (status == 0) puts(sass_context_get_output_string(ctx));
48   else puts(sass_context_get_error_message(ctx));
49
50   // release allocated memory
51   sass_delete_file_context(file_ctx);
52
53   // exit status
54   return status;
55
56 }
57 ```
58
59 ### Compile main.c
60
61 ```bash
62 gcc -c main.c -o main.o
63 gcc -o sample main.o -lsass
64 echo "foo { margin: foo(); }" > foo.scss
65 ./sample foo.scss => "foo { margin: 42px }"
66 ```
67