macros,common-lisp,reader-macro , Read input into string in Lisp reader macro


Read input into string in Lisp reader macro

Question:

Tag: macros,common-lisp,reader-macro

I am trying to make a reader macro that would convert @this into "this". This is what I currently have:

(defun string-reader (stream char)
   (declare (ignore char))
   (format nil "\"~a\"" (read-line stream t nil t))   
)    
(set-macro-character #\@ #'string-reader )

The problem is that this requires that I put a newline after ever @this. I've also tried it with (read), but that just returns the variable test, which has not been set. I can't just hard-code the number of characters after the @ symbol, because I don't know how many there would be. Is there any way to fix this?

Edit: is the only way to do this to loop over read-char and peek-char, reading until I get to #),#\space, or #\Newline?


Answer:

You can try to use read and then look at what it returns:

(defun string-reader (stream char)
   (declare (ignore char))
   (let ((this (let ((*readtable* (copy-readtable)))
                 (setf (readtable-case *readtable*) :preserve)
                 (read stream t nil t))))
     (etypecase this
       (string this)
       (symbol (symbol-name this)))))

(set-macro-character #\@ #'string-reader)

Above would allow @This and @"This", but not @333.

This version just reads a string until whitespace:

(defun read-as-string-until-whitespace (stream)
  (with-output-to-string (out-stream)
    (loop for next = (peek-char nil stream t nil t)
          until (member next '(#\space #\newline #\tab))
          do (write-char (read-char stream t nil t) out-stream))))

(defun string-reader (stream char)
   (declare (ignore char))
   (read-as-string-until-whitespace stream))

(set-macro-character #\@ #'string-reader)

Example:

CL-USER 21 > @this
"this"

CL-USER 22 > @42
"42"

CL-USER 23 > @FooBar
"FooBar"

Related:


Split string in macro


c++,string,split,macros
I've a class name with its namespace, like BasicType::MyType. It's possible to create a macro that split the name and uses only the part after the scope operator (I want to create a MyType object in macro without the first part)? EDIT: I'm using a library with different classes in...

How does this code print odd and even?


c,if-statement,macros,logic
#define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ } int main(void) { int num; printf("Enter a number: "); scanf("%d", &num); if (num & 1) { MACRO(num, "Odd"); } else { MACRO(num, "Even"); } return 0; } Please explain the above code (if/else condition and how...

Append the string provided by __FUNCTION__ macro


c++,macros
I have defined a macro as following: #define ADD_TIME_ENTRY(_name_) m_pTimeMeasurement->addTimeEntry(_name_); Now, I want to pass the function name through ADD_TIME_ENTRY() in whichsoever function I put ADD_TIME_ENTRY() ADD_TIME_ENTRY(__FUNCTION__) works fine for me but now, I want to add "_start" or "_stop" at the end of the function name. I mean, I...

create a macro in sas


macros,sas
I have a report that is generated once a year. each report has the form of the year inside the name - report-2011.xls, report-2012.xls etc. each report contains the following vars: ID, SAL=average monthly salary of that year, Gender (0=male, 1=female), Married (0=not married, 1=married), I need to create a...

Invalid specialized parameter in method lambda list


lisp,common-lisp
I am trying to write a simple coin flip program in Common Lisp. This is the code I have (defun yn (let ht (random 1) (if (eq ht 1) (princ heads) (princ tails)) ) ) It seems simple enough, but I keep getting the error: "Invalid specialized parameter in method...

Understanding NASM Macro


assembly,macros,ffmpeg,nasm
I've come around this macro in a assembly source file and I just can't figure out how it's working. So first I come around this function (hevc_deblock.h): cglobal hevc_v_loop_filter_chroma_8, 3, 5, 7, pix, stride, tc, pix0, r3stride sub pixq, 2 lea r3strideq, [3*strideq] mov pix0q, pixq add pixq, r3strideq TRANSPOSE4x8B_LOAD...

EVAL/APPLY: too many arguments given to F


lisp,common-lisp,clisp
Hello why do i get *** - EVAL/APPLY: too many arguments given to F on function call with nested lists parameter. I cannot figure it out, since I passed a simple nested list. (defun f (L) (cond ((NULL l) nil) ((listp (car L)) (append (F(car L))) (F(cdr L) (car (F...

Insertion into a list doesn't reflect outside function whereas deletion does?


list,lisp,common-lisp
I am new to Lisp. Deletion of an item in a list by a function gets reflected outside the function but insertion doesn't. How can I do the same for insertion? For example (defun test (a b) (delete 1 a) (delete 5 b) (append '(5) b) (member '5 b)) (setq...

how to apply macro on list of lines with vim


linux,vim,macros
let's suppose I want to apply a macro stored on register 1 on lines: 2, 5, 9 but without applying on lines in between. I saw that you can give a range but that is not what I want. I've tried some variation on :2, 5, 9 @1 without success

SAS Concatenate Multiple Variables to Create Data-Driven Macro Statements


sql,macros,sas,append,concatenation
In order to keep my process data-driven, I'm trying to concatenate multiple variables, separated by comma, in order to ultimately put them in a PROC SQL list to call in multiple macro statements that would otherwise clutter my SAS pogram. Take the following sample dataset: DATA TEST; INPUT YEAR CONDITION...

clojure quoting inside let


clojure,macros,eval
Quoting (both syntax and non-syntax) seems to fail to detect vars inside a let statement: (let [foo 1] (eval `(print foo))) This will generate an error or use whatever prior value bound was bound to foo in (def foo bar). Is there a way to make the syntax quote use...

Providing new version of existing macro with parameters


c++,macros,overloading
We have an existing log macro in our code. Lets call it LOG_XXX where XXX is the log level to use, such as LOG_INFO, LOG_DEBUG, LOG_ERROR etc. We stream log messages to the macro: LOG_INFO << "This is a log message."; Under the covers, the macro creates a temporary object...

Updating the window in response to CLIM frame commands


common-lisp,clim,mcclim
While trying to figure out CLIM, I ran into this example program. It's a simple maze game. The author claims to have tested it in LispWorks (and even has #+Genera in there, implying that this program would work on a real Lisp Machine), but I'm trying to get it working...

Can I create a macro or shortuct for a step of XPath in XQuery?


xml,xpath,macros,xquery
Do we have Macros in XQuery? If yes, could you please give an example of their usage. I have the following code let $x := //price/ancestor::* Can I someway, using macros or other things write it as follows: let $x := //price/outward So, the outward should mean ancestor::*...

Is there any way to skip macro replacement(During preprocessing) when macro is used as a variable name?


c++,qt,c++11,macros,qt5
ConflictHeader.h #define _c 6 //This is third party header, canot change, since // there is no sorce code to rebuild testclass.h #ifndef TESTCLASS_H #define TESTCLASS_H #include <QObject> #include "ConflictHeader.h"//Include conflicted header class TestClass : public QObject { Q_OBJECT public: TestClass(QObject *parent); ~TestClass(); private: }; #endif // TESTCLASS_H testclass.cpp #include "testclass.h"...

Why don't I get a warning when I declare a variable with same name in a macro that already exists in a function?


c,macros,ansi
Playing with a macro and thought about the following scenario. Declaring variable in a macro which already exists in function from which this macro has been called, why compiler doesn't complain. When I declare in a code a variable it give me a warning: Redefinition of 'temp' I think that...

How to share same header files between kernel modules and userspace applications.


linux-kernel,macros,linux-device-driver,header-files,ioctl
I want to implement a simple module in which an ioctl() method is used. In the kernel module, I use kernel macros, such as _IO(), _IOWR(), etc., to define my own ioctl sub-commands. In facts, I don't care the actual values of these definitions for that I will always use...

Structuring large Lisp applications


lisp,common-lisp,quicklisp,asdf
I am currently trying to wrap my head around packages, systems & co. I now have read Packages, systems, modules, libraries - WTF? a few times, and I think I'm still having difficulties to get it right. If I simply want to split a Lisp source file into two files,...

EMACS-Live + Slime error at startup


emacs,common-lisp,slime,kubuntu
Ok, I must be missing something obvious. I'm getting stuck since yesterday to launch Emacs-live + slime. I'm using EMACS 24.3.1, installed Emacs-live and it worked well (if I start emacs-live without Slime it works), downloaded Slime-Pack from git and added this line to .emacs-live.el (live-append-packs '(~/.live-packs/slime-pack/)) I'm on a...

Extract Argument from C Macro


c,macros,arguments,c-preprocessor
I have a number of definitions consisting of two comma-separated expressions, like this: #define PIN_ALARM GPIOC,14 I want to pass the second expression of those definitions (14 in the case above) to unary macros like the following: #define _PIN_MODE_OUTPUT(n) (1U << ((n) * 2U)) How can I extract the second...

defining recursive values C


c,macros
#define BLOCK_OFFSET(block) (BASE_OFFSET+(block-1)*block_size) usage lseek(fd, BLOCK_OFFSET(group->bg_inode_table)+(inode_no-1)*sizeof(struct ext2_inode),SEEK_SET); This is a fragment of a code im trying to understand and I have no idea how that definition works. Is it recursive? Can someone explain step by step whats happening in that lseek?...

If strings are vectors, why are they immutable?


lisp,common-lisp
if strings are vectors of characters, and a vector's elements can be accessed using elt, and elt is setf-able - then why are strings immutable?

Local dynamic binding in common lisp


closures,common-lisp,dynamic-binding
Honnestly, I'm not sure I fully understand what it means for a binding to be "dynamic" versus "lexical". But I understand that when I use defvar or defparameterto define a binding, 1. it declares a global variable 2. the binding is declared "special", so that it can be shadowed by...

Why is my C code printing out an extra line of rows?


c,loops,for-loop,macros,printf
#include <stdio.h> #define rows 500 //can define rows as any number int main() { int i,j; for(i=0;i<=rows;++i) { for(j=0;j<(2*i+1);++j) { printf("* "); } printf("\n"); } return 0; } So here is my code, what it does is it prints the number of rows set by #define and creates a right...

where is the text printed by C printf


io,common-lisp,cffi
I happened encounter a trouble with calling C printf function from SBCL via cffi. The problem is when I call printf function, I can't find the output text, just the return value of printf function show on the REPL. But when I quit SBCL, the output text appears on the...

sbcl run-program hang when there is large amount of output from program


common-lisp,hang,sbcl
Recently I find a run-program hang issue of sbcl 1.2.7 (32bits, linux). The code as following (progn (with-open-file (s "test.out" :direction :output :if-exists :supersede) (loop repeat 900 do (write-line (make-string 76 :initial-element #\x) s))) (run-program "/bin/bash" (list "-c" "cat test.out") :output :stream)) That is when the "cat test.out" produce many...

Defining Macros that are equal to functions that return objects in C++


c++,static,macros,singleton
So I have the singleton pattern working the way I want to, I think the main problem is something with pointers and refrences. ("..." represents irrelevent code). Universe.h ... #define TheUniverse Universe::GetInstance (); ... public: static Universe& GetInstance (); ... private: static Universe* x_instance; ... Universe.cpp ... Universe* Universe::x_instance =...

How to control C Macro Precedence


c,macros
#define VAL1CHK 20 #define NUM 1 #define JOIN(A,B,C) A##B##C int x = JOIN(VAL,NUM,CHK); With above code my expectation was int x = 20; But i get compilation error as macro expands to int x = VALNUMCHK; // Which is undefined How to make it so that NUM is replaced first...

Backquote String Interpolation


macros,lisp,common-lisp
Is it possible to use lisp's macro to do string interpolation? For instance, can I make a macro like this: (defmacro test (a) `",a") So that (test abc) returns "abc" as a string? I could probably cheat by quoting it and turning that quote into a string, but that doesn't...

How to test whether an identifier that is accessible only through a #define macro is defined?


c++,c,macros
I have a #define mapping an identifier (a function name) to a new name like this: #define A doStuff This part I cannot do anything about, I have to access "A" since the actual identifier (doStuff here) may change (and this is not under my control). Now the referenced symbol...

Can I create a macro that unrolls loops?


macros,rust
I'm trying to write some fast matrix code in Rust and to do this needs to ensure that loops are unrolled. Is there a way to create a compile-time for-loop? E.g: I want unroll_loop!(f, a, 3); to generate f(a, 0); f(a, 1); f(a, 2); ...

Julia: How do I create a macro that returns its argument?


macros,julia-lang
My question is quite similar to this one, but with a difference. I want to create a macro (or whatever) that behaves this way: julia> @my-macro x + 2 :(x + 2) (note that x + 2 is not enclosed in quotes). Is there something like that in Julia? And...

Parentheses and macro overloading in C++


c++,macros
My codebase has an existing macro: #define SOME_MACRO <macro definition> For some changes I'm making, I want to add a new version of the macro that takes an argument. #define SOME_MACRO(arg1) <macro definition> I see that this question addresses selecting from multiple argument versions of a macro. However, the SOME_MACRO...

Unexpected output printf statement [duplicate]


c,macros,printf,ternary-operator
This question already has an answer here: Why is ā€œiā€ variable getting incremented twice in my program? 8 answers Why outputs of i and j in the following two printf()s are different? #include <cstdio> #define MAX(x,y) (x)>(y)?(x):(y) int main() { int i=10,j=5,k=0; k==MAX(i++,++j); printf("%d %d %d\n",i,j,k); i=10,j=5,k=0; k=MAX(i++,++j); printf("%d...

Read input into string in Lisp reader macro


macros,common-lisp,reader-macro
I am trying to make a reader macro that would convert @this into "this". This is what I currently have: (defun string-reader (stream char) (declare (ignore char)) (format nil "\"~a\"" (read-line stream t nil t)) ) (set-macro-character #\@ #'string-reader ) The problem is that this requires that I put a...

syntax error : missing ')' before 'constant'


c,compiler-errors,macros,syntax-error,c-preprocessor
I have some syntax problems that I don't know how to fix. I'm trying to build some functions to matrix, can someone help me resolve those problems? 1>c:\documents and settings\one\my documents\visual studio 2010\projects\hw3\hw3\q2.c(11): error C2143: syntax error : missing ')' before 'constant' 1>c:\documents and settings\one\my documents\visual studio 2010\projects\hw3\hw3\q2.c(11): error C2143:...

Why do I have to expose a macro implementation's 'use' in the client library?


macros,rust
I'm trying to use a macro I've created in a separate module. With reference to this SO question, I've imported a macro fine. However it seems that I have Update to add macro implementation lib.rs #![macro_use] use std::fmt; use std::ffi::CString; use std::ffi::CStr; use std::str; extern crate libc; pub enum DbaxError...

Creating a function in compile time using a bitmap like macro


c,macros
I have an ansi C function to sum up values from an array, based on patterns. Something like: long sum_all_according_to_pattern(int n, int *values, int *pattern) { long sum = 0; int i = 0; for(;i<n;i++){ if(pattern[i]) sum+=values[i]; } return sum; } Let's say I've a set of patterns such as:...

Use Weka from ImageJ macro: 'path' is required but unset


macros,weka,imagej
I have tried Calling Weka from an ImageJ(Fiji) macro: run("Trainable Weka Segmentation", "open=C:\\input\\test.tif inputfile=C:\input\test.tif path=[Ljava.lang.String;@77e655d8"); But when I run that I get an error message: 'path' is required but unset This line is exactly the line I get when recording a macro and opening test.tif when the Trainable Weka Segmentation...

What does the non-terminating-p argument of set-macro-character do?


macros,common-lisp
Set-macro-character has an optional argument called non-terminating-p. It seems to be used to indicate whether another character should be read after reading the macro character, but the reader algorithm seems to ignore this argument. Is there a difference whether I set it to true or false?

Why is it not advised to define macros in header files?


c++,macros,preprocessor
The Google C++ Style Guide guide advises that macros must not be defined in a .h (header) file. What are the cons of doing it?

Combining multiple template classes to one class using typedef


c++,templates,macros,typedef
I have the following piece of code. Let us have the function declaration and implementation seperate. #include <iostream> class Y1 {}; class Y2 {}; template <class T1, class T2> class A { public: explicit A(); void foo() const; int bar() const; }; template <class T1, class T2> A<T1, T2>::A() {}...

Writing a `define-let` macro, with hygiene


macros,racket,define-syntax,hygiene
I'm trying to write a define-let macro in racket, which "saves" the header of a (let ((var value) ...) ...) , namely just the (var value) ... part, and allows re-using it later on. The code below works as expected: #lang racket ;; define-let allows saving the header part of...

C++ / C #define macro calculation


c++,c,macros
Suppose I have #define DETUNE1 sqrt(7)-sqrt(5) #define DETUNE2 sqrt(11)-sqrt(7) And I call these multiple times in my program. Are DETUNE1 and DETUNE2 calculated every time it is called? Thanks. Please don't downvote this, I really want to know and a search didn't turn up anything definite. ...

What is a common-lisp analogue of python's argparse?


python,common-lisp,argparse
What is a common-lisp analogue of python's argparse library for parsing command-line arguments?

x-macro conditional error - number comparison


c,macros,x-macros
I would like to generate compile time error for X-macro for all X(a, b) where a > b /* X(a, b) */ #define LIST \ X(10, 20) \ X(5, 20) \ X(30, 20) \ X(1, 20) So, generate error for X(30, 20) Is this possible in C? EDIT: example usage...

Macro to push arguments onto stack


visual-c++,assembly,macros
I've been working on a fun little project to mess around with how functions are called and I need a macro to push arguments as it'll be quite time consuming to push the arguments manually for every instance of this obfuscated call. This is my code so far: #define pushargs(...)...